【问题标题】:Taking type of a template class采用模板类的类型
【发布时间】:2010-11-06 09:50:33
【问题描述】:

有没有办法获取模板类的类型,例如

//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)">();

在 C++ 中可以吗?或者有没有捷径可走

【问题讨论】:

  • 不太确定你想要什么。您是否试图从 std::vector 中“提取” int 类型,以便为 CreateData 函数指定的类型是 int 而不是 std::vector
  • 如果你的意思是@Kei 所怀疑的,那么这里就是一个骗子:stackoverflow.com/questions/301203/… :)

标签: c++ class function templates


【解决方案1】:

是 - 使用 boost::typeof

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

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

请注意,您可以给 createData 一个虚拟参数,编译器可以使用它来推断类型。

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

IData* newData = createData(a);

【讨论】:

    【解决方案2】:

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

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

    现在我们可以说:

    IData * id = createData <Foo>();
    

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

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多