需要帮助使用模板识别设计模式

时间:2014-08-16 13:39:57

标签: c++ design-patterns

我最近遇到的特定模板模式使用布尔类型检查来确定要调用的特化。该模式看起来非常熟悉Policy based design,但Policy参数由数据类型控制,而不是使其可配置。

template<
    typename Ty, 
    bool as_type = is_associative<Ty>::value,
    bool it_type = is_iterable<Ty>::value,
    bool pr_type = is_pair<Ty>::value
>
struct brackets
{
    // Any other case is an Error
};
template<typename Ty>
struct brackets<
    Ty,
    true,  //Associative
    true,  //Iterable
    false  //But not a Pair
>   {
    static const char open = '{', close = '}';
};
template<typename Ty>
struct brackets<
    Ty, 
    false, //Not Associative
    true,  //But Iterable
    false  //But not a Pair
>   {
    static const char open = '[', close = ']';
};
template<typename Ty>
struct brackets<
    Ty,
    false, //Neither Associative
    false, //Nor Iterable
    false  //Nor a Pair
>   {
    static const char open = '<', close = '>';
};
template<typename Ty>
struct brackets<
    Ty,
    false, //Neither Associative (actually don't care)
    false, //Nor Iterable
    true   //But a Pair
>
{
    static const char open = '(',  close = ')';
};

社区可以帮我识别模式吗?

1 个答案:

答案 0 :(得分:0)

我想说这与Alexandrescu在type traits technique中确定的Modern C++ design密切相关。

该类根据类型参数做出编译时决策,根据Ty的属性自定义代码。