Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ typename as variable

Suppose I have a template class MyClass. Is it possible to store the type of the template as an variable of the class? If so how? I'm curious if it's possible to do something like this.

Template <typename T> class MyClass;
Template <typename T> class AnotherClass;

MyClass<int> myClassInstance;
AnotherClass<oneInstance.functionThatReturnsTheStoredTypeFromAnInstanceVariableOfMyClass()> anotherClassInstance;

Thanks in advance.

like image 622
thealch3m1st Avatar asked Feb 24 '23 11:02

thealch3m1st


1 Answers

They can be static variables, you can nest typedefs.

template<typename T> class MyClass {
public:
    typedef T type;
};
AnotherClass<MyClass<double>::type> anotherClassInstance;

However, accessing a member variable like you posted is impossible in C++.

like image 55
Puppy Avatar answered Mar 05 '23 10:03

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!