2012-08-29 66 views
3

基础结构的嵌套类型:访问一个模板参数T,即使T是指针

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. 

如何解决此问题?

回答

7

特殊化Bar结构的指针,TO-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; 
}; 
+0

完美!快速答案谢谢:) – Patric

+0

这不会工作。如果我写'Bar 酒吧怎么办?'? – Nawaz

+0

在这一点上,你不得不使用递归的方法来去掉指针,并得到原始类型'T',但这并不是什么OP是请求,所以我没去那么远我的回答。显然,通过模板,您可以创建“完整”的东西来覆盖每个角落的情况,但通常情况下,代码也更加复杂。关于复杂性的好处在于它可以被归纳地证明,但是,仍然,为什么当你只需要一个螺丝刀时撬出一个千斤顶锤?我的回答是我认为OP是螺丝刀级别问题的一个螺丝刀驱动的答案。 – Jason

6

如果你需要做到这一点的情况下,专门的模板会很尴尬,你也可以计算与所用的类型一些相应的模板:

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; 
}; 
+3

可能值得一提的是C++ 11的[std :: remove_pointer](http://en.cppreference.com/w/cpp/types/remove_pointer)。 – juanchopanza

+1

@juanchopanza:'remove_pointer'不做需要什么(只要我可以告诉),因为它不递归删除指针(不是确切的要求是从问题特别明显)。但是谁知道呢......它可能只是帕特里克正在寻找的东西。 – Mankarse

+0

不会像'typename remove_ptr :: type :: inner_type x;'在'Bar'中有诀窍吗?不幸的是我现在不能测试这个... – juanchopanza

相关问题