有没有一种方法将const std::type_info&用作C++中的模板参数?

例如

template < typename T > class A
{
public:
    A(){}
    const std::type_info& type() const
    {
        return typeid(T);
    }
};

template < typename T > void Do()
{
    // Do whatever
}

int main()
{
    A<int> MyA;
    // Something like: Do<MyA.type()>(); or Do<typeid(MyA.type())>();
}

最佳答案

您不能将运行时类型信息用作编译时模板参数。

在C++ 11中,decltype可以为您提供表达式的静态类型:

Do<decltype(MyA)>();

从历史上看,最好的办法是使用另一个函数模板从其参数推断类型:
template <typename T> void Do(T const &) {Do<T>();}

Do(MyA);

关于c++ - C++ type_info作为模板(typename)参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21439278/

10-11 22:50
查看更多