C ++ Structure implicit conversion

I need to declare a large number of simple POD structures that will behave the same, but these are really different types, i.e. not typedefs.

In any case, I just want them to be as simple as possible. But during testing, I saw that the compiler performs some implicit conversions, and I would like to avoid this.

Given this code:

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; } 

Compiled using GCC.

Execution gives me:

 Call with INT :: 3 // Ok Call with INT :: 4 // [1] Call with Struct :: 5.2 // Ok Call with INT :: 6 // [2] 

How can I avoid the implicit conversions [1] and [2]?

thanks

+4
source share
1 answer

As stated in the comment:

Using an explicit keyword for operator T() actually prevent implicit type conversion.

Thus, declaring a structure this way:

 template<typename T> struct Struct { T data; explicit operator T() const { return data; } }; 

will force the compiler to prevent implicit conversion and require that client code specifically request a conversion (i.e. use T(Struct<T>) wherever T is required)

+3
source

Source: https://habr.com/ru/post/1482387/


All Articles