代码之家  ›  专栏  ›  技术社区  ›  Qubeuc

采用模板类的类型

  •  1
  • Qubeuc  · 技术社区  · 15 年前

    例如,有没有一种获取模板类类型的方法

    //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++有可能吗?或者有捷径可供选择吗

    2 回复  |  直到 10 年前
        1
  •  5
  •   Dario    15 年前

    是-使用 boost::typeof

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

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

    注意你可以给 createData 编译器可以用来推断类型的伪参数。

    template<typename T>
    IData* createData(const T& dummy);
    
    IData* newData = createData(a);
    
        2
  •  2
  •   anon    15 年前

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

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

    现在我们可以说:

    IData * id = createData <Foo>();
    

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