问题
A simple example:
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;
};
Is there a way to access the template parameter X
of Small
without using a typedef in the Small
class?
回答1:
Depending on what you're doing, template template parameters might be a better option:
// "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;
回答2:
Yes, define a second "getter" template with partial specialization.
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;
};
Now instead of Small<X>::X
you have typename get_Small_X< Small<X> >::type
.
By the way, _X
is a reserved identifier, so you shouldn't use it for anything. X_
is a better choice.
Advanced topic: template introspection.
While I'm thinking about it, you don't need to define this separately for every template. A single master template should do it.
This compiles in Comeau, I know there are rules about matching template template arguments but I think it's OK… template template arguments are forbidden from the master template in partial specialization.
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;
This only works with "unary" templates but could be adapted in C++0x for the general case.
来源:https://stackoverflow.com/questions/3696286/can-one-access-the-template-parameter-outside-of-a-template-without-a-typedef