According to the documentation, var has an overloaded operator String() function for constructing a String out of a var, but I get an “ambiguous call” error when I try to compile it.
var v1 (1);
int w1 (v1); // operator int(): works fine
DBG (w1);
var v2 ("v2");
String w2 (v2); // operator String(): won't compile
DBG (w2);
Am I missing something here?
Note that I am aware of the toString() method. I was looking to use the operator String() constructor method in a template.
It’s ambiguous because the String constructor can take a bunch of different types, and the var object can produce those types. How does the String constructor know which to use? you can easily just do String w2 (v2.toString());
Why which constructor? the operator String() works when it is asked for a String. But, the String constructor does not know what type is being passed in (since var can be many types), so it can’t ask for a String.
As @Xenakios said, you’re not calling var::operator String()… you’re calling String::String(var) which isn’t defined.
The var::operator String() function allows a var object to be passed to a function that takes a String as an argument, without needing to cast or convert it first:
void print(String message)
{
std::cout << message << std::endl;
}
int main()
{
var v1(1);
print(v1);
var v2("v2");
print(v2);
return 0;
}
// Output:
// 1
// v2