Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why can't use ternary operator with different types when boost variable can hold multiple types?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error C2446 ‘:’: no conversion from ‘std::string’ to ‘int’

>Solution :

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 }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading