1

Is there a way for taking type of a template class, for example

//i have template function
template<typename T>
IData* createData();

//a template class instance
std::vector<int> a;

//using type of this instance in another template
//part in quotation mark is imaginary of course :D
IData* newData = createData<"typeOf(a)">();

is it possible in c++? or is there an shortcut alternative

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Qubeuc
  • 982
  • 1
  • 11
  • 22
  • Not quite sure what you want. Are you trying to 'extract' the int type from std::vector so that the type you're specifying for CreateData function is int instead of std::vector? – Kei Jun 27 '09 at 20:14
  • If you mean what @Kei is suspecting, then here is a dupe: http://stackoverflow.com/questions/301203/extract-c-template-parameters :) – Johannes Schaub - litb Jun 27 '09 at 20:43

2 Answers2

5

Yes - Use boost::typeof

IData* newData = createData<typeof(a)>();

The new standard (C++0x) will provide a builtin way for this.

Note that you could give createData a dummy-argument which the compiler could use to infer the type.

template<typename T>
IData* createData(const T& dummy);

IData* newData = createData(a);
Dario
  • 48,658
  • 8
  • 97
  • 130
2

Not clear what you are asking about. The templates parameter is its type, for example:

template<typename T> IData* createData() {
   return new T();
}

Now we can say:

IData * id = createData <Foo>();

which will create a new Foo instance, which had better be derived from Idata.