可以在没有typedef的情况下访问模板外的模板参数吗?

时间:2010-09-12 19:42:16

标签: c++ templates metaprogramming introspection

一个简单的例子:

template<typename _X> // this template parameter should be usable outside!
struct Small {
   typedef _X X; // this is tedious!
   X foo;
};

template<typename SomeSmall>
struct Big {
   typedef typename SomeSmall::X X; // want to use X here!
   SomeSmall bar;
   X toe;
};

有没有办法在X类中使用typedef来访问Small的模板参数Small

2 个答案:

答案 0 :(得分:8)

是的,定义第二个具有部分特化的“getter”模板。

template< typename >
struct get_Small_X; // base template is incomplete, invalid

template< typename X > // only specializations exist
struct get_Small_X< Small< X > > {
    typedef X type;
};

现在取代Small<X>::X而不是typename get_Small_X< Small<X> >::type

顺便说一句,_X是一个保留的标识符,所以你不应该将它用于任何事情。 X_是更好的选择。


高级主题:模板内省。

在我考虑它时,您不需要为每个模板单独定义它。单个主模板应该这样做。

这在Comeau中编译,我知道有关于匹配模板模板参数的规则,但我认为没关系......在部分特化中 master 模板禁止使用模板模板参数。

template< typename >
struct get_first_type_argument;

template< template< typename > class T, typename X >
struct get_first_type_argument< T< X > > {
    typedef X type;
};

template< typename X >
struct simple;

get_first_type_argument< simple< int > >::type q = 5;

这仅适用于“一元”模板,但在一般情况下可以在C ++ 0x中进行调整。

答案 1 :(得分:4)

根据您正在做的事情,template template parameters可能是更好的选择:

// "typename X" is a template type parameter. It accepts a type.
// "template <typename> class SomeSmall" is a template template parameter.
// It accepts a template that accepts a single type parameter.
template<typename X, template <typename> class SomeSmall> 
struct Big {
   SomeSmall<X> bar; // We pass X to the SomeSmall template.
   X toe; // X is available to this template.
}; 

// Usage example:

template<typename X>
struct Small { 
   X foo; 
};

struct MyType {};

// The foo member in Small will be of type MyType.
Big<MyType, Small> big;
相关问题