Search code examples
c++void

How do i make a void method know what type to use?


So my question is very simple but i can't find how to do it . I created this method on .cpp

void Message_Test::Integers(const uint64_t &_value){}

and in the .hpp

void Integers(const uint64_t &_value)

I'm passing a uint64_t value { 35000 } to the method like so Integers(value), but i also would like to use this method with a uint16_t value { 35000 }, without having to create multiple methods.

I would like to know if there is a way to change my entire parameter so it knows if its a uint64_t or a 32,16,etc ...


Solution

  • Given that you want a const reference, assuming you had a good reason for it to be a reference, you can not allow any implicit conversion to happen. If the function is called with an uint16_t the compiler will create a temporary uint64_t and pass the address of that. For any valid reason to use a reference to a primitive type this would be fatal.

    I don't think you have any other choice than use a template

    template <typename T>
    void Integers(const T &_value){ ... }
    

    Note that the template must be in the header.

    When you store the value reference somewhere for later use (That's why it's a reference, right? Because otherwise just pass by value.) you then have to figure out how to store it, e.g. with std::variant. Or template the whole class. Depends on the context.