c++classconstructordecltype

C++ decltype with arguments (class with constructor)


Let's say I have a class T with a constructor T(int b) and child Tchild with a similar constructor Tchild(int b).

How can I use decltype with the argument?

For example:

Let's pretend I don't know those next 2 types:

T abc{};
Tchild def{};

std::vector<*T> vec;
vec.push_back(new decltype(Tchild));  

How can I make new decltype with this constructor -> Tchild(int b) ?

I'm a newbie and my question may be very dumb. I tried to find an answer but I couldn't, maybe I'm asking a bad question.


Solution

  • You say T and Tchild have constructors that take int parameters. So you need to pass in int values for them, eg:

    T abc{1};
    Tchild def{2};
    

    T abc{}; and Tchild def{}; will not compile unless those classes also define default constructors, which you did not describe.

    In any case, new decltype(Tchild) makes no sense as Tchild is already a type, so you could have just written new Tchild. You probably meant new decltype(def) instead.

    But, you still have to provide a int value if you want the Tchild(int b) constructor to be called, eg:

    vec.push_back(new decltype(def){3});