#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:
Basector initializes constants so I can't use the ctor body.- This is the only derived class doing the
boolmagic, so changingBaseto 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
bthere - I need a runtime decision.
Aucun commentaire:
Enregistrer un commentaire