• C++17:static_assert实现


    引言

    static_assert是从C++0x开始引入的关键字,static_assert可让编译器在编译时进行断言检查。static_assert的语法格式:

    static_assert( constant-expression, string-literal ); // C++11 
    static_assert( constant-expression ); // C++17
    
    • 1
    • 2
    • constant-expression
      可转换为布尔值的整型常量表达式。 如果计算出的表达式为零 (false),则显示 string-literal 参数,并且编译失败,并出现错误。 如果表达式不为零 (true),则 static_assert 声明无效。
    • string-literal
      当 constant-expression 参数为零时显示的消息。 该消息是编译器的基本字符集中的一个字符串(不是多字节或宽字符)。C++ 17前需要的constant-expression消息参数,C++17变成可选。意味着C++17以后static_assert声明不再需要第二个参数。

    static_assert中文译为静态断言,此名称是相对与assert而言的,assert中文译为断言或动态断言。C++0x之前没有动态断言和静态断言之分,因为C++98仅支持assert这一种断言方式。

    static_assert(sizeof(void *) == 4, "64-bit code generation is not supported.");
    
    • 1

    assert为C++98从C语言继承而来的断言方式,assert的定义即语法格式(Visual Studio 2022):

    #ifdef NDEBUG
    
        #define assert(expression) ((void)0)
    
    #else
    
        _ACRTIMP void __cdecl _wassert(
            _In_z_ wchar_t const* _Message,
            _In_z_ wchar_t const* _File,
            _In_   unsigned       _Line
            );
    
        #define assert(expression) (void)(                                                       \
                (!!(expression)) ||                                                              \
                (_wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) \
            )
    
    #endif
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    当未定义 NDEBUG 时,C 运行库的发布版本和调试版本中均启用了 assert 宏。 定义时 NDEBUG ,该宏可用,但不会评估其参数,并且不起作用。 启用后assert 宏会调用 _wassert 用于实现。此定义巧妙的利用C语言的||短路求值特性,只有expression为false,_wassert才会运行并抛出错误结束进程,否则_wassert不会运行,就不会抛出错误。

    assert(std::is_same_v<int, int>);   // Error: assert 不接收二个参数
    assert((std::is_same_v<int, int>)); // OK: 一个参数
    std::complex<double> c;
    assert(c == std::complex<double>{0, 0}); // Error: assert 不接收二个参数
    assert((c == std::complex<double>{0, 0})); // OK: 一个参数
    
    • 1
    • 2
    • 3
    • 4
    • 5

    为何引入static_assert

    也许现在的你和我最初的想法一样,认为static_assert很多余。我们带着这个疑问,看看下面这个案例。

    案例:某家公司的一个app需要Microsoft,Google和Phone设备3种联系人读取,在最初1.0版本时,他们仅支持Microsoft和Phone设备两种方式的联系人读取;从2.0开始他们开始支持Google联系人的读取。

    • 1.0版本App
    enum ContactType
    {
    	MICROSOFT,  // 微软联系人 
    	PHONE,      // 本地手机联系人
    	ALL         // 所有联系人
    };
    
    // 本地文件名称
    static const std::string LOCAL_FILE_NAME = "contact_type.txt";
    
    // 读取操作
    typedef bool (*readOperator)();  
    
    // 读取Microsoft
    bool readMicrosoftContact()
    {
    	std::cout << "read microsoft contact...";
    	return true;
    }
    
    // 读取本地phone
    bool readPhoneContact()
    {
    	std::cout << "read phone contact...";
    	return true;
    }
    
    // 读取本地phone
    bool readAllContact()
    {
    	std::cout << "read phone contact...";
    	return true;
    }
    
    static const std::unordered_map<int, readOperator> g_readOperators{
    	{
    		ContactType::PHONE, readPhoneContact
    	},
    	{
    		ContactType::MICROSOFT, readMicrosoftContact
    	},
    	{
    		ContactType::ALL, readAllContact
    	}
    };
    
    int main()
    {
    	int contactType = ContactType::ALL;
    
    	std::ifstream readLocalFile(LOCAL_FILE_NAME);
    	if (readLocalFile.good())   // 文件存在
    	{
    		readLocalFile >> contactType;
    		readLocalFile.close();
    	}
    	else
    	{
    		std::ofstream outputLocalFile(LOCAL_FILE_NAME);
    		std::cout << "please enter contact type: 0 Microsoft,1 Phone, 2 ALL: ";
    		std::cin >> contactType;
    		outputLocalFile << contactType;
    		outputLocalFile.flush();
    		outputLocalFile.close();
    	}
    
    	auto iter = g_readOperators.find(contactType);
    	if (g_readOperators.end() != iter)
    	{
    		iter->second();
    	}
    
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    此时用户首次运行可执行程序,输入:1表示读取本地Phone联系人,程序输出

    please enter contact type: 1
    read phone contact...
    
    • 1
    • 2
    • 2.0版本App
    enum ContactType
    {
    	MICROSOFT,  // 微软联系人 
    	GOOGLE,     // google联系人
    	PHONE,      // 本地手机联系人
    	ALL         // 所有联系人
    };
    
    // 本地文件名称
    static const std::string LOCAL_FILE_NAME = "contact_type.txt";
    
    // 读取操作
    typedef bool (*readOperator)();  
    
    // 读取Microsoft
    bool readMicrosoftContact()
    {
    	std::cout << "read microsoft contact...";
    	return true;
    }
    
    // 读取google
    bool readGoogleContact()
    {
    	std::cout << "read google contact...";
    	return true;
    }
    
    // 读取本地phone
    bool readPhoneContact()
    {
    	std::cout << "read phone contact...";
    	return true;
    }
    
    // 读取本地phone
    bool readAllContact()
    {
    	std::cout << "read phone contact...";
    	return true;
    }
    
    static const std::unordered_map<int, readOperator> g_readOperators{
    	{
    		ContactType::PHONE, readPhoneContact
    	},
    	{
    		ContactType::MICROSOFT, readMicrosoftContact
    	},
    	{
    		ContactType::GOOGLE, readGoogleContact
    	},
    	{
    		ContactType::ALL, readAllContact
    	}
    };
    
    int main()
    {
    	int contactType = ContactType::ALL;
    
    	std::ifstream readLocalFile(LOCAL_FILE_NAME);
    	if (readLocalFile.good())   // 文件存在
    	{
    		readLocalFile >> contactType;
    		readLocalFile.close();
    	}
    	else
    	{
    		std::ofstream outputLocalFile(LOCAL_FILE_NAME);
    		std::cout << "please enter contact type: 0 Microsoft,1 GOOGLE, 2 Phone, 3 ALL: ";
    		std::cin >> contactType;
    		outputLocalFile << contactType;
    		outputLocalFile.flush();
    		outputLocalFile.close();
    	}
    
    	auto iter = g_readOperators.find(contactType);
    	if (g_readOperators.end() != iter)
    	{
    		iter->second();
    	}
    
    
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86

    可执行程序支持了GOOGLE联系人,用户升级可执行程序,然后可执行程序会直接启动不需要用户输入自己的contact类型,但是用户这时候发现,可执行程序展示的联系人非自己的Phone联系人,产生了生成问题。

    read google contact...
    
    • 1
    • App存在的问题

    这个问题在于用户第一次输入1表示PHONE,升级2.0后1不在表示PHONE,而表示GOOGLE了。

    关键这种问题有时候是无法感知的,也很难定位。不过幸好有了static_assert。我们可以采用静态断言来解决这类问题。我们在1.0版本添加static_assert如下:

    enum ContactType
    {
    	MICROSOFT,  // 微软联系人 
    	PHONE,      // 本地手机联系人
    	ALL         // 所有联系人
    };
    
    static_assert(0 == ContactType::MICROSOFT);
    static_assert(1 == ContactType::PHONE);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    这样2.0版本修改ContactType枚举,static_assert就会提示编译错误。我们为每个版本增加枚举,添加新的断言而不修改老版本的断言,此种方式可完美的解决枚举定义不一致问题。例如,在枚举中间添加GOOGLE,static_assert(1 == ContactType::PHONE)就会有编译错误提示。

    enum ContactType
    {
    	MICROSOFT,  // 微软联系人 
    	GOOGLE,     // google联系人
    	PHONE,      // 本地手机联系人
    	ALL         // 所有联系人
    };
    
    static_assert(0 == ContactType::MICROSOFT);
    static_assert(1 == ContactType::PHONE);
    static_assert(1 == ContactType::GOOGLE);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    如何使用static_assert

    static_assert可以应用于命名空间和作用域内(作为块声明),也可应用于类体内(作为成员声明)。

    命名空间static_assert

    命名空间中的static_assert立刻求值并断言。例如:

    static_assert(sizeof(void *) == 4, "64-bit code generation is not supported.");
    
    • 1

    类中的static_assert

    static_assert 声明具有模板类中。编译器将在声明 static_assert 声明时检查该声明,但不计算 constant-expression 参数,直到类模板实例化式才求值并断言。但是对于普通非模板类,编译器会立刻求值并且断言。

    #include 
    #include 
    
    template <class CharT, class Traits = std::char_traits<CharT> >
    class basic_string 
    {
        static_assert(std::is_trivially_copyable<CharT>::value, "Template argument CharT must be a POD type in class template basic_string");
        // ...
    };
    
    class EmptyClass
    {
        static_assert(2 == sizeof(int), "int must is 2 bytes");
    };
    
    int main()
    {
        basic_string<char> bs;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    编译提示错误:

    1> main.cpp(21,21): error C2338: static_assert failed: 'EmptyClass* must is 2 bytes'
    
    • 1

    块中的static_assert

    static_assert 声明具有函数模板内。编译器将在声明 static_assert 声明时检查该声明,但不计算 constant-expression 参数,直到函数模板实例化式才求值并断言。但是对于非模板函数,编译器会立刻求值并且断言。

    template<typename T>
    inline void doStuff(T val) 
    {
        static_assert(!std::is_volatile<T>::value, "No volatile types plz");
        //...
    }
    
    int test(int a)
    {
        static_assert(2 == sizeof(int), "test int must is 2 bytes");
        return 0;
    }
    
    int main()
    {
        volatile char sometext[261];
        doStuff(sometext);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    编译提示错误:

    1> main.cpp(21,21):  error C2338: static_assert failed: 'test int must is 2 bytes'
    
    • 1

    static_assert实现

    利用C++语言的语法规则实现静态断言的方式非常多,这里只介绍两种static_assert实现方式。第一种通过除0编译错误实现静态断言;第二种开源库Boost内置的BOOST_STATIC_ASSERT中断言机制,利用sizeof操作符实现静态断言。

    “除0”静态断言

    “除0”静态断言,利用“除0"会导致编译器报错这个特性来实现静态断言。

    #define assert_static(e)               \
      do {                                 \
           enum{assert_static__ = 1 /(e)}; \
      } while(false)
    
    • 1
    • 2
    • 3
    • 4

    Boost静态断言

    BOOST_STATIC_ASSERT宏利用c++规范,不完整类型即不可实例化的类型,在对其进行sizeof运算时提示编译错误。

    template<bool x>struct STATIC_ASSERTION_FAILURE;
    template<>struct STATIC_ASSERTION_FAILURE<true>{};
    template<int x>struct static_assert_test{};
    
    #defineBOOST_STATIC_ASSERT(B)                                      \
    	typedef static_assert_test<sizeof(STATIC_ASSERTION_FAILURE<B>> \
    	boost_static_assert_typedef_##__LINE__
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    总结

    本文从static_assert和assert的定义切入,分别详细介绍static_assert引入的原因,如何使用static_assert,最后以static_assert实现作为本文的结束。希望本文的介绍可以加深你对静态断言static_assert的理解。

  • 相关阅读:
    C语言编程陷阱(五)
    MySQL 三大日志(bin log、redo log、undo log)
    华为Hcia-数通学习(更改策略)
    31【window 对象】
    在线问诊 Python、FastAPI、Neo4j — 创建 检查节点
    黑马苍穹外卖6 清理redis缓存+Spring Cache+购物车的增删改查
    Fiddler Orchestra用户指南:打造高效协同调试利器
    1022 D进制的A+B
    第二章 计算机算术
    哈希表 | 快乐数 | leecode刷题笔记
  • 原文地址:https://blog.csdn.net/liuguang841118/article/details/127854946