4

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.

6
  • Did you try to compile and test it? did it work? Commented Jul 25, 2011 at 5:31
  • Are you trying to get AnotherClass<MyClass<int>>, or AnotherClass<int> ? Commented Jul 25, 2011 at 5:40
  • @NirMH, I would have tried to compile it if I would have known how to store the type passed in to the template as a variable in the instance of the class, which looks like it's not exactly possible. Commented Jul 25, 2011 at 8:58
  • @Useless, I was just curious if it's possible to store the type as an instance variable and then use the value of that instance variable to pass on to another class template as a type or create other variables using it, much like the Class type in Objective-C where you can do stuff like, Class someClass = [someObject class]; id newInstanceOfSomeClass = [[someClass alloc] init]; In case you are an Obj-C programmer, my example is flawed, doesn't exactly work for CoreFoundation bridged stuff for ex, NSString *instance... [instance class] returns NSCFString; Commented Jul 25, 2011 at 9:20
  • The typedef mechanism used by @DeadMG is what you want then (and this technique is used a lot in the STL) ... it just isn't called an instance variable, because it doesn't vary, and is really a property of the type rather than the instance. Commented Jul 25, 2011 at 11:39

1 Answer 1

8

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++.

Sign up to request clarification or add additional context in comments.

6 Comments

+1, you need to edit your code; it should be class/struct MyClass.
I wouldn't call the name of a nested type a variable.
Oh darn it. Is there any way to create something like the Class type in Objective-C ?
@Luc, the answer is correct, if you go with what OP wants. We don't have to capture every word of the question especially when the asker is novice. Here OP may have meant variable as type. DeadMG, you need to put type in public access.
@iammilind My comment has nothing to do with the OP, I'm only commenting on this particular answer. Do you call i in const int i = 42; a variable? Do you call f in void f(); a variable? Issues of terminology may not be fun but are important.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.