Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : Make multiple constructors with the same argument types

I would like to make a class with several constructors of the same type. As this is not directly possible, is there a simple way to define readable "dummy" types such as the class could look like:

class Myclass
{
    MyClass(Orange, std::string & name, float size);
    MyClass(Apple, std::string & name, float size);
    MyClass(Banana, std::string & name, float size);
}

I could define Orange, Apple and Banana as struct typedefs, but is there a more convenient way?

Thanks

like image 296
galinette Avatar asked Oct 30 '25 16:10

galinette


2 Answers

The standard library does this in various places actually, for example std::piecewise_construct_t. Their standard is to provide...

struct something_t {};

constexpr something_t something = something_t();
like image 170
David Avatar answered Nov 02 '25 08:11

David


Yes you can tag dispatch to overload the constructor arbitrarily:

struct Orange{};
struct Apple{};
struct Banana{};

class MyClass
{
    MyClass(Orange, std::string & name, float size){}
    MyClass(Apple, std::string & name, float size){}
    MyClass(Banana, std::string & name, float size){}
};

int main()
{
    std::string name("Fred");   
    MyClass myObject(Orange(), name, 10.0f);

    return 0;
}
like image 43
PeterSW Avatar answered Nov 02 '25 07:11

PeterSW