基本结构:
struct Foo{
typedef int inner_type;
};
template<class T>
struct Bar{
typename T::inner_type x;
};
主要内容:
Bar<Foo>(); // Compiles OK
Bar<Foo*>(); // Doesn't compile: template T becomes a pointer-to-class and is not a valid class anymore.
如何解决这个问题?
最佳答案
将 Bar
结构特化为指向 T
类型的指针:
//non-specialized template for generic type T
template<class T>
struct Bar{
typename T::inner_type x;
};
//specialization for pointer-to-T types
template<class T>
struct Bar<T*>{
typename T::inner_type x;
};
关于c++ - 访问模板参数 T 的嵌套类型,即使 T 是指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12171810/