C ++ Struct隐式转换

时间:2013-05-23 12:42:44

标签: c++ c++11 struct implicit-conversion

我需要声明大量简单的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]?

由于

1 个答案:

答案 0 :(得分:3)

根据评论中的要求:

使用operator T()的显式关键字实际上会阻止隐式类型转换。

因此,以这种方式声明结构:

template<typename T>
struct Struct {
    T data;

    explicit operator T() const { return data; }
};

将使编译器阻止隐式转换,并要求客户端代码专门请求转换(即在需要T的地方使用T(Struct<T>)