C++ 可以在部分专门化中模拟默认模板参数吗?
默认模板参数可用于模拟模板声明中复杂类型表达式的别名。例如:C++ 可以在部分专门化中模拟默认模板参数吗?,c++,templates,metaprogramming,C++,Templates,Metaprogramming,默认模板参数可用于模拟模板声明中复杂类型表达式的别名。例如: template <typename X, typename Y = do_something_with<X>::type, typename Z = some_other_thing_using<X, Y>::type struct foo { ... X, Y, Z ... }; 我解决这个问题的方法是使用辅助类型: template <typename
template <typename X,
typename Y = do_something_with<X>::type,
typename Z = some_other_thing_using<X, Y>::type
struct foo { ... X, Y, Z ... };
我解决这个问题的方法是使用辅助类型:
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>
{ ... };
模板
已启用结构栏{
typedef typename使用::type Y做某事;
typedef typename some_other_thing_using::type Z;
静态常量布尔值=某些条件::值;
};
模板
结构栏::类型>
{ ... };
但出于各种原因(其中有人希望避免使用单独的类型,这会使我的工作复杂化),我希望存在更好的解决方案。有什么想法吗?也许你可以将这种区别固定在一个基类中:
template <typename X, typename Y, bool>
struct BaseImpl { /* ... */ };
template <typename X, typename Y>
struct BaseImpl<X, Y, true> { /* ... */ };
template <typename X, typename Y = typename weird_stuff<X>::type>
struct Foo : BaseImpl<X, Y, some_condition<X, Y>::value>
{
// common stuff
};
模板
结构BaseImpl{/*…*/};
模板
结构BaseImpl{/*…*/};
模板
结构Foo:BaseImpl
{
//普通的东西
};
默认参数不会模拟任何内容。它们提供默认值。作为记录,“专门化的模板参数列表不应包含默认模板参数值”[C++11:14.5.5/8]@LightnessRacesinOrbit,您的意思是指出这个问题在C++11中没有改变,还是其他什么?@AJG:只是在正确的断言中附加一个引用。
template <typename X, typename Y, bool>
struct BaseImpl { /* ... */ };
template <typename X, typename Y>
struct BaseImpl<X, Y, true> { /* ... */ };
template <typename X, typename Y = typename weird_stuff<X>::type>
struct Foo : BaseImpl<X, Y, some_condition<X, Y>::value>
{
// common stuff
};