I am trying to write a function that will set the first argument to the value of the second argument. However, when the second argument is a container class, I want it to set the first argument to the first element of the container. I found this question which answers a similar problem, however, I can not seem to get it to work in my case.
When I compile this code I get an error saying that SetVar is ambiguous. Is there anyway to get the functionality working?
Here is my code so far…
#include <iostream>
#include <vector>
template<typename T1,typename T2>
static void SetVar(T1& a, const T2 &b, typename T2::const_iterator= T2().begin()){
//Check to make sure b contains an element.
if(b.begin()!=b.end()) a=*b.begin();
}
template<typename T1,typename T2>
static void SetVar(T1& a, const T2 &b,...){
a=b;
}
int main(int argc, const char * argv[])
{
int x;
int y=5;
std::vector<int> z;
z.push_back(1);
z.push_back(3);
SetVar(x, y);
//Should print 5
std::cout<<x<<"\n";
SetVar(x, z);//<---SetVar is ambiguous
//Should print 1
std::cout<<x<<"\n";
return 0;
}
Passing argument to an ellipsis does make a function overload less preferred than one that has an actual parameter for the same argument, but that doesn’t come up here because there is no third argument in your calls.
I would use
enable_iffor both:It’s still possible for the above to be ambiguous, but only if both conditions are true, which means a weird container or implicit conversion is going on – and in that case I would want the compiler to warn me of the confusion.