Search code examples
c++compiler-errorsoverloadingambiguous-call

Ambiguity issue when deducing function call


I have the following bit of code which has two versions of the function foo. I'd like if a variable is passed for the foo that takes an AVar type to be called otherwise if a const is passed for the AConst version to be called.

#include <iostream>

template <typename T>
struct AConst
{
   AConst(T x):t(x){}
   const T t;
};

template <typename T>
struct AVar
{
   AVar(const T& x):t(x){}
   const T& t;
};

template <typename T>
void foo(AConst<T> a) { std::cout << "foo AConst\n"; }

template <typename T>
void foo(AVar<T>   a) { std::cout << "foo AVar\n";   }

int main()
{
   int i = 2;

   foo(1);
   foo(i);

   return 0;
}

Currently the compiler gives me an ambiguity error. Not sure how to resolve it.

UPDATE: Based on Leonid's answer with a slight modification, here is the following solution which works as required:

template <typename T>
void foo_x(AConst<T> a) { std::cout << "foo AConst\n"; }

template <typename T>
void foo_x(AVar<T>   a) { std::cout << "foo AVar\n";   }


template <typename T>
void foo(const T& a) { foo_x(AConst<T>(a));}

template <typename T>
void foo(T& a) { foo_x(AVar<T>(a));}

Solution

  • Compiler can not deduce your T.
    To help him, simplify parameter type:

    template <typename T> 
    void foo(const T& a) { AConst<T> aa(a); std::cout << "foo AConst\n"; }
    
    template <typename T> 
    void foo(T& a) {  AVar<T> aa(a); std::cout << "foo AVar\n";   }