gpt4 book ai didi

c++ - 为什么使用 constexpr、__PRETTY_FUNCTION__ 和 char * 的这两段代码会有不同的结果?

转载 作者:IT老高 更新时间:2023-10-28 22:14:10 25 4
gpt4 key购买 nike

我有这段代码,如果你注释掉注释“但这不起作用?!”的行,它编译得很好,但如果你不这样做,编译器会产生错误。

至少,gcc 8.2 generates an error .

但是,他们看起来和我一模一样。有什么问题?这是法律法规吗?

template <int x>
struct test_template {
static int size() { return x; }
};

constexpr int ce_strlen(char const *s)
{
int i = 0;
while (s[i]) ++i;
return i;
}

int joe()
{
constexpr int plen = ce_strlen(__PRETTY_FUNCTION__); // This works
test_template<plen> a; // This declaration is valid.
test_template<ce_strlen(__PRETTY_FUNCTION__)> b; // But this doesn't work?!
return a.size() + b.size();
}

我在尝试提出 a way to create profile tags for an intrusive profiling system at compile time 时遇到了这个问题.我成功了,但我的最终代码不涉及使用 ce_strlen

最佳答案

确实,正如评论中所讨论的,这是 GCC 中的一个错误,但我想我会对该错误的性质提出一些额外的见解。在海合会 NEWS file有这一行:

  • __FUNCTION__ and __PRETTY_FUNCTION__ are now treated as variables by the parser; previously they were treated as string constants. So code like printf (__FUNCTION__ ": foo") must be rewritten to printf ("%s: foo", __FUNCTION__). This is necessary for templates.

但是 __PRETTY_FUNCTION__ 并不是真正的变量,它是在解析器中处理的特殊情况,正如我们在 constexpr.c 中看到的那样:

    case DECL_EXPR:
{
tree decl = DECL_EXPR_DECL (body);
if (TREE_CODE (decl) == USING_DECL
/* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
|| DECL_ARTIFICIAL (decl))
return NULL_TREE;
return error_mark_node;
}

如果它真的是一个变量,我们希望它通过与这些相同的测试用例:

constexpr const char* s2 = "TEST";
constexpr const char* s3 = s2;
test_template<ce_strlen("TEST")> c;
test_template<ce_strlen(s2)> d;
test_template<ce_strlen(s3)> e;

关于c++ - 为什么使用 constexpr、__PRETTY_FUNCTION__ 和 char * 的这两段代码会有不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52472000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com