如何在编译时静态比较两个字符串 [英] How can you compare two character strings statically at compile time
问题描述
我想创建一个宏,它可以比较2个字符串,并发出编译时错误,如果条件不满足。这可能是一个编译时断言。
I would like to create a macro which can compare 2 strings, and emit a compile time error if the condition isn't met. This could be though of as a compile time assertion.
我不知道我该怎么做。
例如:
STATIC_COMPARE("THIS STRING","THIS STRING") -> would emit a compile time error
STATIC_COMPARE("THIS STRING","THIS OTHER STRING) -> wouldn't emit a compile time error.
宏将类似于
#define STATIC_COMPARE(str1,str2) if (str1==str2) emit an error with a message
所以我想问题归化在编译时可以比较2个字符串。
So I guess the question boils down to being able to compare the 2 strings at compile time.
推荐答案
可以使用C ++ 11通过使用 constexpr
function:
You can do this with C++11 by using a constexpr
function:
constexpr bool strings_equal(char const * a, char const * b) {
return *a == *b && (*a == '\0' || strings_equal(a + 1, b + 1));
}
(请参阅一个演示)
在C ++ 11之前不可能做到这一点,许多编译器将编译等号字符串作为指针的警告在这些编译器上,直接比较字符串就足够了,因为它们都将被作为等指针来计算。
It's not possible to do this prior to C++11, with the caveat that many compilers will compile equal string literals to be a pointer to the same location. On these compilers it's sufficient to compare the strings directly since they will both be evaluated as equal pointers.
这篇关于如何在编译时静态比较两个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!