采取模板类的类型

时间:2021-07-22 21:39:48

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

在c ++中有可能吗?还是有一个捷径替代品

2 个解决方案

#1


Yes - Use boost::typeof

是的 - 使用boost :: typeof

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

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

新标准(C ++ 0x)将为此提供内置方式。

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

请注意,您可以为createData提供一个伪参数,编译器可以使用该参数来推断类型。

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

IData* newData = createData(a);

#2


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

不清楚你在问什么。 templates参数是其类型,例如:

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.

这将创建一个新的Foo实例,最好从Idata派生。

#1


Yes - Use boost::typeof

是的 - 使用boost :: typeof

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

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

新标准(C ++ 0x)将为此提供内置方式。

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

请注意,您可以为createData提供一个伪参数,编译器可以使用该参数来推断类型。

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

IData* newData = createData(a);

#2


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

不清楚你在问什么。 templates参数是其类型,例如:

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.

这将创建一个新的Foo实例,最好从Idata派生。