Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template and ambiguous function call

Some code I have no control over has a number of overloaded functions which accepts different types

i.e.

setValue(int)
setValue(std::string)
setValue(bool)

And I have a template function which would idealy take any one of these types and pass it on to the correct setValue function.

template <class T>
do_something(T value) {
    ...
    setValue(value);

But I get this error

error: call to member function 'SetValue' is ambiguous

Is there anything I can do to work around this problem without copy and pasting my code for each type like the writers of setValue have?

like image 603
user2675345 Avatar asked Jul 30 '26 05:07

user2675345


1 Answers

by defining you own SetValue with exact match and forwarding to the correct overload.

void setValue(int i) { setValue(static_cast<double>(i)) }

or (if you have a lot of "setValue" functions with same type) you may help the compiler to choose which overload to use like this:

void setValue(char a);
void setValue(double a);

template <typename T>
struct TypeToUseFor
{
    typedef T type;
};

template <>
struct TypeToUseFor<int>
{
    typedef double type;
};

template <class T>
void func(T value)
{
    setValue(static_cast<typename TypeToUseFor<T>::type>(value));
//    setValue(value);
}

int main() {
    func(0);   // int -> ?
    func('0'); // exact match
    func(0.0); // exect match
    func(0.f); // float -> double

    return 0;
}
like image 52
Jarod42 Avatar answered Aug 01 '26 17:08

Jarod42