【发布时间】:2019-09-03 05:52:45
【问题描述】:
这段代码当然是愚蠢的,但我只是为了说明问题而写的。 这里是:
#include <iostream>
using namespace std;
struct foo {
int a = 42;
template <typename T>
operator T* () {
cout << "operator T*()\n";
return reinterpret_cast<T*>(&a);
}
template <typename T>
operator const T* () const {
cout << "operator const T*() const\n";
return reinterpret_cast<const T*>(&a);
}
template <typename T>
T get() {
cout << "T get()\n";
return this->operator T();
}
};
int main() {
foo myFoo;
cout << *myFoo.get<const int*>() << '\n';
}
使用 Visual Studio 2019(ISO C++17,/Ox)编译时的输出为:
T get()
operator const T*() const
42
gcc 8.3 (-std=c++17, -O3) 的输出是:
T get()
operator T*()
42
所以我想知道为什么这两个编译器选择在给定这段代码的情况下调用不同的 const 限定转换?
如果我将get() 更改为get() const,则两者都调用const 版本的转换。但是 VS 通过从未标记为 const 的方法调用 const 转换不是违反标准吗?
编辑:
为了消除对reinterpret_cast、here's a version without it 的一些混淆,它们仍然在两个编译器上产生相同的输出。
【问题讨论】:
-
因为其中一个是错误的。
myFoo.get不是const,所以我希望调用非const转换版本。 -
@Someprogrammerdude
foo::get<int const*>致电foo::operator<int const>。返回值确实是const int*。 -
您的代码似乎说明的问题比问题的实际内容要多得多。例如,您真的需要
reinterpret_casts 来重现输出吗? -
@user463035818 不这么认为,我通常只是用
reinterpret_cast编写指针转换,因为它只是获取地址并将其视为指向另一种类型的指针,而static_cast可以改变行为(但在这种情况下不是),而且 C 风格的指针转换很丑 :) -
呃...
reinterpret_cast和 c 风格的演员表一样丑陋。 Afaik 他们之间没有任何区别
标签: c++ operator-overloading constants operator-keyword