Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在编译时静态比较两个字符串_C++_Xcode_Macros_Compiler Errors_Gnu - Fatal编程技术网

C++ 如何在编译时静态比较两个字符串

C++ 如何在编译时静态比较两个字符串,c++,xcode,macros,compiler-errors,gnu,C++,Xcode,Macros,Compiler Errors,Gnu,我想创建一个宏,它可以比较两个字符串,如果不满足条件,就会发出编译时错误。这可以看作是编译时断言 我不知道我怎么能做到这一点 例如: 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. 宏看起来像 #de

我想创建一个宏,它可以比较两个字符串,如果不满足条件,就会发出编译时错误。这可以看作是编译时断言

我不知道我怎么能做到这一点

例如:

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

因此,我想问题归结为能够在编译时比较这两个字符串。

您可以使用
constexpr
函数。以下是C++14的方法:

constexpr bool equal( char const* lhs, char const* rhs )
{
    while (*lhs || *rhs)
        if (*lhs++ != *rhs++)
            return false;
    return true;
}

constexpr bool strings_equal(char const * a, char const * b) {
    return *a == *b && (*a == '\0' || strings_equal(a + 1, b + 1));
}
()


在C++11之前不可能做到这一点,但需要注意的是,许多编译器将编译相等的字符串文本作为指向同一位置的指针。在这些编译器中,直接比较字符串是足够的,因为它们都被当作相等的指针。

这可以用CysExPR在C++ 11中完成。通过定义递归函数,可以检查字符串是否相等

constexpr bool isequal(char const *one, char const *two) 
{
    return (*one && *two) ? (*one == *two && isequal(one + 1, two + 1)) : (!*one && !*two);
}

static_assert(isequal("foo", "foo"), "this should never fail");
static_assert(!isequal("foo", "bar"), "this should never fail");
感谢Johannes Schaub,我使用了这段代码,您可以看到完整的文章,因此从C++17开始的文章是可用的。它支持constexpr comparison:

#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;
}
#包括
constexpr bool strings_equal(char const*a,char const*b){
返回std::string_视图(a)==b;
}
int main(){
静态断言(字符串等于(“abc”、“abc”)、“字符串等于”);
静态断言(!字符串等于(“abc”、“abcd”),“字符串不等于”);
返回0;
}

您是否假设字符串文字池也与在同一网站上使用coliru相关。用1y在叮当声上试过,效果很好。将删除我的评论。我正在尝试使其在Xcode中工作-无法。也许有另一种方法可以在该环境中创建静态断言。我找到了一些资源,但无法使其发挥作用。“注意,许多编译器将编译相等的字符串文字作为指向同一位置的指针。”字符串文字没有内存位置。@Nils字符串文字创建具有静态存储持续时间的未命名数组。这个数组有一个内存位置,这就是文本有效引用的位置。因此,是的,一个文本会导致内存位置存在,它可以与任何其他指针进行比较。