【问题标题】:Using conditional definitions with variadic templates使用带有可变参数模板的条件定义
【发布时间】:2014-03-20 08:11:18
【问题描述】:

如果我有一个模板函数,它接受已知数量的模板参数,我可以使用enable_if 语句以及is_base_of 之类的东西来限制合法类型。例如:

template <typename T>
typename enable_if<is_base_of<BaseClass, T>::value, void>::type
function() {
    // do stuff with T, which is ensured to be a child class of BaseClass
}

现在假设我们想对可变参数模板做同样的事情 - 检查以确保所有类型都是特定基类的子类。

template <typename... T>
/* What goes here? */
function() {
    // do stuff with the T types, which are ensured to be child classes of BaseClass
}

您将如何编写这个条件定义?

【问题讨论】:

    标签: c++ templates c++11 variadic-templates enable-if


    【解决方案1】:

    您可以使用以下 type_traits:

    template <typename Base, typename T, typename... Ts>
    struct are_base_of :
        std::conditional<std::is_base_of<Base, T>::value, are_base_of<Base, Ts...>,
                         std::false_type>::type
    {};
    
    template <typename Base, typename T>
    struct are_base_of<Base, T> : std::is_base_of<Base, T> {};
    

    然后使用

    template <typename... Ts>
    typename std::enable_if<are_base_of<BaseClass, Ts...>::value, void>::type
    function() {
        // do stuff with Ts, which is ensured to be a child class of BaseClass
    }
    

    【讨论】:

    • +1 片刻我没有看到基础扩展(不要问;这里很晚)。制作精良。
    • 酷 - 所以 are_base_of 结构递归地从 is_base_of 继承 Ts 中的每个类型。谢谢贾罗德!
    猜你喜欢
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2015-12-14
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多