【发布时间】:2016-02-16 17:27:18
【问题描述】:
我遇到了 C2440 错误:
C:\code>cl test.cpp /EHsc
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
test.cpp
test.cpp(18) : error C2440: 'initializing' : cannot convert from 'D<TYPE,SELECTOR>' to 'int'
with
[
TYPE=int,
SELECTOR=int
]
Ambiguous user-defined-conversion
当我尝试使用 Visual Studio 10 编译以下测试代码时,它似乎与 clang -Weverything 和 armcc 一起工作正常。
这是否有特殊原因不起作用,除了“不要那样做”之外还有其他解决方法吗?
#include <iostream>
template <typename TYPE, typename SELECTOR = int> struct D {
TYPE x;
D() : x(2) {}
D(TYPE X) : x(X) {}
operator const TYPE&() const { return x; }
};
template <typename TYPE> struct D<TYPE, int> : public D<TYPE, char> {
D() : D<TYPE, char>(3) {}
operator TYPE&() { return D<TYPE, char>::x; }
};
int main() {
D<int, int> test3;
int t3 = test3;
D<int, char> test2;
int t2 = test2;
std::cout << +t3 << " " << +t2 << "\n"; // Expected output "3 2" (which we get from clang)
return 0;
}
编辑:我知道D<TYPE, int> 案例提供了一个左值,而D<TYPE, non-int> 案例只提供了一个右值。这是故意的。
【问题讨论】:
-
在 gcc 上运行良好
-
那么派生类中的
operator int&()是否从基类中隐藏了operator const int&(),或者它是一个重载?谁知道呢! -
如果签名相同,则它会覆盖但可能与命名空间规范相匹配。这个例子与 const 不同,因此可以调用 const 和非 const 版本。
标签: c++ templates visual-c++ visual-c++-2010