Dan*_*vil 9 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;
};
Run Code Online (Sandbox Code Playgroud)
有没有办法在不使用类中的typedef X的Small情况下访问模板参数Small?
是的,定义具有部分特化的第二个"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;
};
Run Code Online (Sandbox Code Playgroud)
现在而不是Small<X>::X你typename get_Small_X< Small<X> >::type.
顺便说一句,_X是一个保留标识符,所以你不应该用它做任何事情.X_是一个更好的选择.
高级主题:模板内省.
在我考虑它时,您不需要为每个模板单独定义它.单个主模板应该这样做.
这个编译在Comeau中,我知道有关于匹配模板模板参数的规则,但我认为没关系...... 在部分特化中主模板禁止使用模板模板参数.
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;
Run Code Online (Sandbox Code Playgroud)
这仅适用于"一元"模板,但在一般情况下可以在C++ 0x中进行调整.
根据您的工作,模板模板参数可能是一个更好的选择:
// "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;
Run Code Online (Sandbox Code Playgroud)