【问题标题】:Enum-only templated class仅枚举模板化类
【发布时间】:2014-11-23 01:05:03
【问题描述】:

如果为特定模板参数提供的不是强类型枚举(即枚举类),是否有任何方法可以确保模板化类无法编译?

【问题讨论】:

    标签: c++ templates c++11 enums


    【解决方案1】:

    使用特征和static_assert

    template <class T>
    using is_scoped_enum = std::integral_constant<bool, !std::is_convertible<T, int>{}
                                                      && std::is_enum<T>{}>;
    
    template <typename T>
    struct myTemplate
    {
       static_assert( is_scoped_enum<T>{}, "Invalid type argument!" );
    };
    

    (取自this answer。)
    Demo

    【讨论】:

    • 哇,很干净。我预计需要更多的魔法 - 谢谢!只要系统允许我就接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多