struct B; struct A { operator B(); }; struct B { B operator + (B) {return B();} }; A::operator B() { return B(); } int main() { A x; B y; y+x; // Как запретить неявное преобразование для данного оператора/ группы операторов? };
|
1 answer
Implicit conversion can be disabled as follows:
struct A { explicit operator B(); };
Now it’s only possible to convert A
to B
If you want to leave the implicit conversion as a whole, but in particular cases it is undesirable, then you can use this trick:
#include <type_traits> //... struct B { template<typename TB, typename=std::enable_if_t<std::is_same<TB, B>::value>> B operator + (TB) { return B(); } };
- @hero, you can explicitly
C-cast
type (static_cast
orC-cast
) - ixSci - Why in the first case write
expilicit operator B()
if you can simply not write it? - hero - @hero, if you don’t write it, you cannot convert
A
toB
, and if you makeexplicit
, you can convert it, but only explicitly (as I indicated in the previous comment) - ixSci - Now it's clear, thanks - hero
- Writes [Error] only declarations of constructors can be 'explicit' - hero
|