c++ - 访问模板参数 T 的嵌套类型,即使 T 是指针

标签 c++ templates pointers

基本结构:

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/

相关文章:

c - 函数调用后输出不同的值?

c++ - Makefile 模式规则无法匹配

c++ - int和char之间的数据转换

c++ - 如何在 C++ 中创建自定义整数序列

c++ - 使用C++对ipv6地址进行比较操作

c++ - friend 声明声明了一个非模板函数

C++1y/C++14 : Converting static constexpr array to non-type template parameter pack?

c++ - 如何使用类的模板参数作为链表的模板参数传递?

c++ - 为什么没有 C++ 的 DELETE 宏的原因

c - 在循环中创建一个新指针 C