【发布时间】:2013-05-23 12:42:43
【问题描述】:
我需要声明大量简单的 POD 结构,它们的行为相同,但实际上是不同的类型,即不是 typedef。
无论如何,我只是想让它们尽可能简单。但是在测试时我看到编译器执行了一些隐式转换,我想避免这种情况。
鉴于此代码:
template<typename T>
struct Struct {
T data;
operator T() const { return data; }
};
void fun(Struct<float> value)
{
cout << "Call with Struct :: " << value << endl;
}
void fun(int value)
{
cout << "Call with INT :: " << value << endl;
}
int main(int, char**)
{
fun(3);
fun(4.1f);
fun(Struct<float>{5.2});
fun(Struct<double>{6.3});
return 0;
}
使用 GCC 编译。
执行给了我:
Call with INT :: 3 // Ok
Call with INT :: 4 // [1]
Call with Struct :: 5.2 // Ok
Call with INT :: 6 // [2]
如何避免隐式转换 [1] 和 [2]?
谢谢
【问题讨论】:
-
所以你希望它只调用
int重载,如果你给出一个int? -
@sftrabbit 是也不是。最重要的是[2],我要的是禁止Struct -> int转换。
-
好吧,如果我错了,请纠正我,但仍然有
explicit关键字。 -
你可以使用这样的东西
operator int() =delete; -
那么你想要什么结果呢?编译器错误?
标签: c++ c++11 struct implicit-conversion