简体   繁体   English

宏中的typedef char

[英]typedef char in a macro

I am reading the machine learning library dlib which is written in C++. 我正在阅读用C ++编写的机器学习库dlib。 I came across a code in a header file which defines a bunch of macros. 我在头文件中遇到了定义了一系列宏的代码。 I have difficulties understanding the following code 我在理解以下代码时遇到困难

#ifndef BOOST_JOIN
#define BOOST_JOIN( X, Y ) BOOST_DO_JOIN( X, Y )
#define BOOST_DO_JOIN( X, Y ) BOOST_DO_JOIN2(X,Y)
#define BOOST_DO_JOIN2( X, Y ) X##Y
#endif
//  a bunch of other code

namespace dlib
{
template <bool value> struct compile_time_assert;
template <> struct compile_time_assert<true> { enum {value=1};  };
// a bunch of other definitions
}

#define COMPILE_TIME_ASSERT(expression) \
    DLIB_NO_WARN_UNUSED typedef char BOOST_JOIN(DLIB_CTA, __LINE__)[::dlib::compile_time_assert<(bool)(expression)>::value] 

what I do not understand is that 我不明白的是

  1. what does the last line in the above code do? 上面代码的最后一行是做什么的?

  2. typedef char here is so weird, I don't understand it at all. 这里的typedef char很奇怪,我一点也不明白。

  3. After substitution for BOOST_JOIN , it becomes DLIB_CTA__LINE__[1] , why it is an array? 替换为BOOST_JOIN ,它变为DLIB_CTA__LINE__[1] ,为什么是数组? Is it legal? 合法吗

This is a C++03 static assert, or at least the workaround used to simulate it. 这是C ++ 03静态断言,或者至少是用于模拟它的解决方法。

The following defines a struct only if value is true, else the type is not defined. 以下仅在value为true时定义结构,否则未定义类型。

template <bool value> struct compile_time_assert;
template <> struct compile_time_assert<true> { enum {value=1};  };

Which means compile_time_assert<true>::value is perfectly correct, but compile_time_assert<false>::value is a compilation error since compile_time_assert<false> is not defined. 这意味着compile_time_assert<true>::value完全正确,但是compile_time_assert<false>::value是编译错误,因为未定义compile_time_assert<false>

Now, the core of the assert: 现在,断言的核心是:

DLIB_NO_WARN_UNUSED typedef char BOOST_JOIN(DLIB_CTA, __LINE__) ::dlib::compile_time_assert<(bool)(expression)>::value]

This defines a typedef on a char array of size 1, only if expression evaluates to true. 仅当expression计算结果为true时,才在大小为1的char数组上定义typedef。 If the expression evaluates to false, then there is a compile time error and the name of the typedef is a hint about the error. 如果表达式的计算结果为false,则说明存在编译时错误,并且typedef的名称是有关该错误的提示。

Note that there are some variants of this. 请注意,这有一些变体。 Some use a negative or null size instead of a compilation error, ie they define the following: 有些使用负数或null大小而不是编译错误,即它们定义了以下内容:

template <> struct compile_time_assert<false> { enum { value = -1 };  };

But actually there is a way concise formulation of this (you can see it in this question ): 但实际上有一种简洁的表述方式(您可以在此问题中看到它):

typedef char static_assert_something[expression ? 1 : -1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM