【发布时间】:2012-03-15 21:38:46
【问题描述】:
默认模板参数可用于模拟模板声明中复杂类型表达式的别名。例如:
template <typename X,
typename Y = do_something_with<X>::type,
typename Z = some_other_thing_using<X, Y>::type
struct foo { ... X, Y, Z ... };
但是,部分特化可能没有默认模板参数 ([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>
{ ... };
我解决它的方法是使用辅助类型:
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 const bool value = some_condition<X, Y, Z>::value;
};
template <typename X>
struct bar <std::vector<X>,
typename enable_if_c<
bar_enabled<X>::value
>::type>
{ ... };
但出于各种原因(其中包括希望避免使用单独的类型,这会使我的工作复杂化),我希望存在更好的解决方案。有什么想法吗?
【问题讨论】:
-
默认参数不模拟任何东西。它们提供默认值。
-
在此声明,“特化的模板参数列表不应包含默认模板参数值”
[C++11: 14.5.5/8] -
@LightnessRacesinOrbit,你的意思是指出这个问题在 C++11 或其他方面没有改变吗?
-
@AJG:只需在您的正确断言上附上引文即可。
标签: c++ templates metaprogramming