字符串相等时的编译时断言 [英] Compile-time assert for string equality

查看:106
本文介绍了字符串相等时的编译时断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用模板吗?

有两个字符串常量.它们来自不同模块中的定义.它们必须相等,否则将引发编译时错误.我可以使用模板吗?

There are two string constants. They come from defines in different modules. They must be equal, or I shall raise compile-time error if they are not equal. Can I do this using templates?

#define MY_STRING "foo"
CompileAssertIfStringsNotEqual(MY_STRING, HIS_STRING);

P.S.我被假定为"abc" [0]是常量表达式而感到迷惑.它不是.语言中的古怪遗漏.如果"abc" [0]被表达,那就可能了.

P.S. I was deluded by assuming that "abc"[0] is constant expression. It is not. Weird omission in the language. It would be possibe had "abc"[0] been constand expression.

推荐答案

这仅适用于C ++ 0x. C ++ 03没有机会.

This is only possible with C++0x. No chance with C++03.

适用于C ++ 0x的Constexpr函数.以下内容适用于GCC4.6,但是该标准并未明确允许它使用,并且已经在考虑进行一些小的措辞以使该规范允许它使用.

Constexpr function for C++0x. The following works with GCC4.6, however the Standard is not explicit in allowing it, and a small wording tweak was and is being considered to make the spec allow it.

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");

在所有递归中,要求编译器跟踪对字符串文字字符的引用.只是最后一次从字符中读取是明确禁止的(如果,着眼睛,可以将其读取为IMO).如果您的编译器不想接受上述简单版本,则可以使宏声明数组,然后进行比较

The compiler is required to track the reference to characters of the string literals already, throughout all the recursions. Just the final read from characters isn't explicitly allowed (if you squint, you can read it as being allowed, IMO). If your compiler doesn't want to accept the above simple version, you can make your macro declare arrays and then compare those

#define CONCAT1(A, B) A ## B
#define CONCAT(A, B) CONCAT1(A, B)

#define CHECK_EQUAL(A, B) \
  constexpr char CONCAT(x1, __LINE__)[] = A, \
                 CONCAT(x2, __LINE__)[] = B; \
  static_assert(isequal(CONCAT(x1, __LINE__), CONCAT(x2, __LINE__)), \
     "'" A "' and '"  B "' are not equal!")

那很好.

CHECK_EQUAL("foo", "foo"); /* will pass */
CHECK_EQUAL("foo", "bar"); /* will fail */

请注意,CHECK_EQUAL可以在函数内部使用. FCD确实进行了更改,以允许constexpr函数在其调用替换中从自动数组读取.参见 DR1197 .

Note that CHECK_EQUAL can be used inside of functions. The FCD did make a change to allow constexpr functions to read from automatic arrays in their invocation substitution. See DR1197.

这篇关于字符串相等时的编译时断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆