C++: how to choose the constructor depending on the condition?

后端 未结 5 1460
长发绾君心
长发绾君心 2021-01-24 19:30

Assume I have a class with different constructors:

class A
{
public:
    A(char* string)
    {
        //...
    }

    A(int value)
    {
        //..
    }

           


        
5条回答
  •  难免孤独
    2021-01-24 19:56

    If the type has a default constructor, you can default-construct an object, immediately destruct it, and then construct it again with the appropriate constructor via placement-new:

    A a;
    a.~A();
    if (isTrue())
    {
        new(&a) A("string");
    }
    else
    {
        new(&a) A(10);
    }
    

    The C++ standard has several examples similar to the above, just search for .~ and ->~.

    Note that this is ultra evil. If your code ever gets reviewed, you are probably going to get fired.

提交回复
热议问题