Why wouldn’t the following compile:
void f(int8_t a)
{
}
void f(int16_t a)
{
}
typedef boost::variant<int8_t, int16_t> AttrValue;
int main()
{
AttrValue a;
a = int8_t(1);
f(a);
}
With the compiler error:
error C2665: 'f' : none of the 2 overloads could convert all the argument types
could be 'void f(int8_t)'
or 'void f(int16_t)'
However, this is OK:
std::cout << a; // f(a);
Where is Where is std::ostream &operator<<(std::ostream &, const AttrValue &) defined and why is it defined?
Overload resolution happens at compile time, when your
boost::variantinstance could contain either type, so the compiler has no way of knowing whether to callvoid f(int8_t)orvoid f(int16_t).std::cout << aworks because in either case it’s calling the same function,std::ostream &operator<<(std::ostream &, const AttrValue &), which inside dispatches on the runtime type of the instance.You need to write a visitor to perform the dispatching: