#include <iostream>
template <typename T>
struct Wrapper {
operator T const &() const & {
std::cout << "Wrapper::operator T const &() const &\n";
return _obj;
}
operator T&() & {
std::cout << "Wrapper::operator T&() &\n";
return _obj;
}
operator T&&() && {
std::cout << "Wrapper::operator T&&() &&\n";
return std::move(_obj);
}
private:
T _obj;
};
struct Test {
Test& operator=(Test const &test) {
std::cout << "Test& Test::operator=(Test const &)\n";
return *this;
}
Test& operator=(Test &&test) {
std::cout << "Test& Test::operator=(Test &&)\n";
return *this;
}
};
int main() {
Test test;
Wrapper<Test> wrapperTest;
test = wrapperTest; // OK for all
test = std::move(wrapperTest); // OK for GCC and ICC, not for Clang and VC++
return 0;
}
VC++ :
(34): 错误 C2593: 'operator =' 不明确
(26): 注意: 可以是 'Test &Test::operator =(Test &&)'
(25): 或者是 'Test &Test::operator =(const Test &)'
(69): 试图匹配参数列表 '(Test, Wrapper)' 时
========== 构建: 成功 0 个,失败 1 个,最新的 0 个,跳过 0 个 ==========
Clang :
:34:7: 错误: 使用重载运算符 '=' 不明确 (操作数类型为 'Test' 和 'typename std::remove_reference<<T>>::type' (又名 'Wrapper'))
test = std::move(wrapperTest); // 对于 GCC 和 ICC 可行,对于 Clang 和 Microsoft Visual C++ 不可行
~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~
:25:8: 候选函数
Test& operator=(Test const &test) { std::cout << "Test& Test::operator=(Test const &)\n"; return *this; }
^
:26:8: 候选函数
Test& operator=(Test &&test) { std::cout << "Test& Test::operator=(Test &&)\n"; return *this; }
^
1 个错误生成。
g++
示例在哪里?你提供了VC++
的示例,但是你问题的标题说的是g++
。到底是哪个?Visual Studio C++和GNU g++是不同的编译器。 - Thomas Matthewsoperator=()
存在二义性。那有什么不同呢? - Thomas Matthews&
和&&
函数限定符是什么意思?我第一次见到它们。 - Post Self