c++ - 如何使用与成员初始值设定项列表一起使用的 static_assert

标签 c++ c++11 enums c++14 static-assert

我想使用 static_assert 对我的类的配置实现各种限制。早些时候,我只使用一个枚举,并且只允许一个需要所述枚举的构造函数来对我的类实现限制。如果我有类似下面的内容并且范围是从 0 到 4,这很好用,但是一旦我有 0 到 500 的范围,那么使用枚举就变得笨拙了。

一些类.h

class Some_Class {
    public:
        Some_Class(const unsigned int param);
    private:
        const unsigned int member_param;
};

Some_Class.cpp

Some_Class::Some_Class(const unsigned int param) : member_param(param) {
    static_assert(member_param < 500, "Param must be less than 500.");
};

main.cpp

Some_Class foo4(125); // OK
Some_Class foo5(500); // Should fail at compile time.

这是 GCC 在使用 C++14 编译时抛给我的:

1>  Some_Class.cpp: In constructor 'Some_Class::Some_Class(unsigned int)':
1>C:\some_path\Some_Class.cpp(3,2): error : non-constant condition for static assertion
1>    static_assert(member_param < 500, "Param must be less than 500.");
1>    ^
1>C:\some_path\Some_Class.cpp(3,2): error : use of 'this' in a constant expression

最佳答案

constexpr 中不能使用参数值。

你必须以某种方式提交编译时值:

  • 为您的整个类(class)制作模板:

    template<unsigned int size>
    class Some_Class {
        static_assert(size < 500, "Size should be less than 500");
    public:
        constexpr unsigned int member_param = size;
    };
    
  • 传递一个 integral_constant:

    template <unsigned int N>
    using uint_c = std::integral_constant<unsigned int, N>;
    
    class Some_Class {
    public:
        template<unsigned int size>
        Some_Class(uint_c<size>) : member_param(size)
        {
            static_assert(size < 500, "Size should be less than 500");
        }
    private:
        unsigned int member_param;
    };
    

关于c++ - 如何使用与成员初始值设定项列表一起使用的 static_assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930464/

相关文章:

c++ - std::initializer_list 会导致生命周期问题吗?

mysql - 数据模型: Having separate table for a field vs having it as a column in the main table

C++ (de) 序列化项目的 vector 顺序

C++ 单指针上的多个 new

c++ - 错误 C2039 : 'vector' : is not a member of 'std'

C++ 从命令行用 clang 编译,但不使用 CMake

c++ - 包含不同大小的 vector 的结构,cpp

c++ - 如何测量编译/链接周期中花费在磁盘 I/O 上的时间?

c# - 如何将 ENUM 值转换为 String 从 View 到 Controller

swift - 在 Swift 中,如何在协议(protocol)扩展中使用通用枚举类型?