mardi 20 juillet 2021

Can operands to `a?b:c` have different types? What's the best alternative?

#include <iostream>
#include <string>


struct Base
{
    Base(int)
    {
        std::cout << "int\n";
    }

    Base(std::string)
    {
        std::cout << "string\n";
    }
};


struct S : Base
{
    S(bool b)
    : Base{ b ? int{} : std::string{} }
    {}
};


int main()
{
    S(42);
    S("fortytwo");
}

There are are a couple of compilation error with this code but the more interesting is

operands to ?: have different types: int and std::string.

Constraints:

  • Base ctor initializes constants so I can't use the ctor body.
  • This is the only derived class doing the bool magic, so changing Base to accommodate it would be ... undesirable.

What now? The point of this code is for the derived class S call one of the overloaded ctors of Base based on a bool.

Considered solutions:

  • An IIFE could possibly work but be rather ugly and long.
  • A helper function - same.
  • Templating S and passing b there - I need a runtime decision.

Aucun commentaire:

Enregistrer un commentaire