Avn*_*arr 11 c++ macros xcode gnu compiler-errors
我想创建一个可以比较2个字符串的宏,如果不满足条件则发出编译时错误.这可能是编译时断言.
我不知道怎么能这样做.
例如:
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.
Run Code Online (Sandbox Code Playgroud)
宏会看起来像
#define STATIC_COMPARE(str1,str2) if (str1==str2) emit an error with a message
Run Code Online (Sandbox Code Playgroud)
所以我想问题归结为能够在编译时比较2个字符串.
Jan*_*ann 13
从 C++17 std::string_view 开始可用。它支持 constexpr 比较:
#include <string_view>
constexpr bool strings_equal(char const * a, char const * b) {
return std::string_view(a)==b;
}
int main() {
static_assert(strings_equal("abc", "abc" ), "strings are equal");
static_assert(!strings_equal("abc", "abcd"), "strings are not equal");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
cdh*_*wie 12
您可以使用constexpr
函数使用C++ 11执行此操作:
constexpr bool strings_equal(char const * a, char const * b) {
return *a == *b && (*a == '\0' || strings_equal(a + 1, b + 1));
}
Run Code Online (Sandbox Code Playgroud)
(见演示)
这是不可能做C++在此之前11,需要提醒的是许多编译器将编译等于字符串文字是一个指向同一位置.在这些编译器是足够的琴弦直接比较,因为他们都将作为平等的指针进行评估.
你可以使用constexpr
功能.这是C++ 14方式:
constexpr bool equal( char const* lhs, char const* rhs )
{
while (*lhs || *rhs)
if (*lhs++ != *rhs++)
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
演示.
归档时间: |
|
查看次数: |
4687 次 |
最近记录: |