默认模板参数可用于模拟模板声明中复杂类型表达式的别名.例如:
template <typename X,
typename Y = do_something_with<X>::type,
typename Z = some_other_thing_using<X, Y>::type
struct foo { ... X, Y, Z ... };
Run Code Online (Sandbox Code Playgroud)
但是,部分特化可能没有默认模板参数([C++11: 14.5.5/8]),因此这个技巧不起作用.您可能会问自己为什么体内的typedef不起作用,答案是别名需要在类体之前的范围内,以便进行条件化启用; 例如:
template <typename T, typename Enable = void>
struct bar;
// Wishful thinking:
template <typename X,
typename Y = do_something_with<X>::type,
typename Z = some_other_thing_using<X, Y>::type>
struct bar <std::vector<X>,
typename enable_if<
some_condition<X, Y, Z>
>::type>
{ ... };
Run Code Online (Sandbox Code Playgroud)
我解决它的方式是使用辅助类型:
template <typename X>
struct bar_enabled {
typedef typename do_something_with<X>::type Y;
typedef typename some_other_thing_using<X, Y>::type Z;
static …Run Code Online (Sandbox Code Playgroud)