gpt4 book ai didi

c++ - 将 const 限定符应用于模板参数时的不同编译器行为

转载 作者:IT老高 更新时间:2023-10-28 12:51:52 26 4
gpt4 key购买 nike

考虑以下示例 (godbolt):

#include <iostream>

template <typename T>
const T *as_const(T *p) { return p; }

void f() {}

template <typename T>
void g(T *) { std::cout << "A"; }

template <typename T>
void g(const T *) { std::cout << "B"; }

int main() {
g(as_const(&f));
}

GCC 和 Clang 都可以编译它,但生成的可执行文件会产生不同的输出:用 GCC 编译的版本打印 A,而用 Clang 编译的版本打印 B

你能解释一下这个区别吗?

更新:正如@VTT 所指出的,即使 as_const 被删除,也会观察到相同的差异。

最佳答案

您似乎遇到了尚未解决的标准缺陷。所以回答“哪个编译器是对的?”目前还不完全清楚。

该问题已提交委员会讨论:

It is not clear whether the following is well-formed or not:

void foo(){}

template<class T>
void deduce(const T*) { }

int main() {
deduce(foo);
}

Implementations vary in their treatment of this example.

http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584 ,但建议的解决方案不是 N4141 或 N4659 的一部分。

请注意,您通常不能有指向 const 函数类型的指针;如果您认为我引用的示例格式不正确,则 gcc 将是正确的。它确实拒绝该示例,并在 OP 中选择非常量版本作为唯一可行的重载。

如果 clang (其中 claims to implement the proposed resolution )否则是正确的,我不确定。我想一旦委员会用我们可以使用的一些规范性措辞解决了这个问题,我们就必须重新讨论那个讨论。

然而,

The consensus of CWG was that the cv-qualification of the argument and parameter must match, so the original example should be rejected.

(对上述问题的注释)似乎表明 gcc 是正确的,问题将得到解决,有利于它的行为。

关于c++ - 将 const 限定符应用于模板参数时的不同编译器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083051/

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