即使T是指针,也可以访问模板参数T的嵌套类型

Pat*_*ric 4 c++ templates pointers

基础结构:

struct Foo{
    typedef int inner_type;
};

template<class T>
struct Bar{
    typename T::inner_type x;
};
Run Code Online (Sandbox Code Playgroud)

主要:

Bar<Foo>();  // Compiles OK
Bar<Foo*>(); // Doesn't compile: template T becomes a pointer-to-class and is not a valid class anymore. 
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

Jas*_*son 8

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;
};
Run Code Online (Sandbox Code Playgroud)


Man*_*rse 7

如果您需要在专门化模板很尴尬的情况下执行此操作,您还可以计算要使用的类型以及一些适当的模板:

template<class T> struct remove_all_pointers {
    typedef T type;
};
template<class T> struct remove_all_pointers<T*> {
    typedef typename remove_all_pointers<T>::type type;
};
template<class T> struct remove_all_pointers<T* const> {
    typedef typename remove_all_pointers<T>::type type;
};
template<class T> struct remove_all_pointers<T* volatile> {
    typedef typename remove_all_pointers<T>::type type;
};
template<class T> struct remove_all_pointers<T* const volatile> {
    typedef typename remove_all_pointers<T>::type type;
};

struct Foo {
    typedef int inner_type;
};

template<class T>
struct Bar {
    typename remove_all_pointers<T>::type::inner_type x;
};
Run Code Online (Sandbox Code Playgroud)

  • 可能值得一提的是C++ 11的[std :: remove_pointer](http://en.cppreference.com/w/cpp/types/remove_pointer). (4认同)