gpt4 book ai didi

c++ - 涉及通用引用的过载解决方案

转载 作者:可可西里 更新时间:2023-11-01 16:39:31 24 4
gpt4 key购买 nike

对于下面的代码:

class A {};

template <typename T> void f(T& a) {}
template <typename T> void f(T&& a) {}

int main() {
A a;
f(a);
}

clang++ 将调用绑定(bind)到第一个重载,而 g++ 报告不明确的调用。哪一个采取了正确的行动?

最佳答案

gcc 4.9.0 20140302 和 clang 3.5 (trunk 202594) 都正确地选择了第一个版本。作为hvd好心给了我the references in comments :

If, for a given type, deduction succeeds in both directions (i.e., the types are identical after the transformations above) and both P and A were reference types (before being replaced with the type referred to above):
— if the type from the argument template was an lvalue reference and the type from the parameter template was not, the argument type is considered to be more specialized than the other; otherwise,
— if the type from the argument template is more cv-qualified than the type from the parameter template (as described above), the argument type is considered to be more specialized than the other; otherwise,
— neither type is more specialized than the other.


顺便看看The Universal Reference/Overloading Collision Conundrum视频为什么重载通用引用是个坏主意。简而言之,请考虑以下示例:

#include <iostream>
#include <utility>

struct A { bool guts_stolen; };

void steal_guts(A&& a) {
a.guts_stolen = true;
}

template <typename T> void f(const T& a) {
// ^^^^^ note the const!
std::cout << "T&\n";
}

template <typename T> void f(T&& a) {
std::cout << "T&&\n";
steal_guts(std::move(a));
}

int main() {
A a{ false };
f(a);
std::cout << "Guts stolen? " << std::boolalpha << a.guts_stolen << std::endl;
}

如果你运行程序,它会打印

T&&
Guts stolen? true

这根本不是您仅通过查看 A a{ false } 所期望的; f(a);.

关于c++ - 涉及通用引用的过载解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22248157/

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