是否可以在部分特化中模拟默认模板参数?

ajg*_*ajg 6 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 ... };
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 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>
    { ... };
Run Code Online (Sandbox Code Playgroud)

但由于各种原因(其中包括想要避免单独的类型,这使我正在做的事情复杂化),我希望存在更好的解决方案.有任何想法吗?

Ker*_* SB 4

也许您可以将区别粘贴到基类中:

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
};
Run Code Online (Sandbox Code Playgroud)