Home > Software design >  C : Get Template of an existing object
C : Get Template of an existing object

Time:05-10

Sorry for the headline. I have no idea for a better headline. I have this code:

template <class T>
class Object
{
    public:
    T a1;
};

Object<short> myObj;

int main() {
    myObj.a1 = 10000;
    // ......
}

(I know, this is not perfect code. It is a sample code to show my problem.)

Now I need to create a new variable in main() function. The variable must have the same type like the template parameter of myObj (short in sample code). Is there a way to do this?

int main() {
    myObj.a1 = 10000;

    myObj.TEMPLATE_PARAM_WHATEVER myNewVar = 99; // myNewVar must have the type short
}

CodePudding user response:

Is there a way to do this?

Yes it is possible using a typedef or an alias declaration. One crude example is shown below:

template <class T>
class Object
{
    public:
    using parameterType = T;
    T a1;
};

Object<short> myObj;

int main() {
    myObj.a1 = 10000;
    decltype(myObj)::parameterType newVar = 99;
       
}

Demo.

Note that in this particular example you can also just write:

decltype(myObj.a1) newVar = 99;

CodePudding user response:

If Object is under your control, you can add a member typedef:

// In `class Object`:
using type = T;
// in `main()`:
decltype(myObj)::type myNewVar = 99;

Here's another option that doesn't require modifying class Object:

decltype(myObj.a1) myNewVar = 99;

If Object doesn't actually have a member variable with the right type, you can still extract the template argument:

template <typename T> struct ObjectType {};
template <typename T> struct ObjectType<Object<T>> {using type = T;};
template <typename T> using ObjectType_t = typename ObjectType<T>::type;
// In `main()`:
ObjectType_t<decltype(myObj)> myNewVar = 99;
  • Related