Home > Software engineering >  why can't use ternary operator with different types when boost variable can hold multiple types
why can't use ternary operator with different types when boost variable can hold multiple types

Time:08-10

I have something like below, but unable to compile it. I don't get it why I can't have different type when my variable can hold different types?

My code:

#include <boost/variant.hpp>
#include <iostream>

typedef boost::variant<int, float, double, std::string> MultiType;

int main() {
    int a = 1;
    std::string b = "b";
    bool c = true;
    MultiType d = c ? a : b;
    return 0;
}

The error:

Error C2446 ':': no conversion from 'std::string' to 'int'

CodePudding user response:

The expression c ? a : b has to have a type. There is no common type between std::string and int, so that expression is invalid.

There is a common type between std::string and MultiType, and between int and MultiType, so c ? MultiType{ a } : b is a valid expression, as is c ? a : MultiType{ b }

  • Related