How to remove a function from overload resolution?

I want to have an instance of my class transform in intwhen using the assignment operator. So I wrote this code:

struct X
{
    X() = default;
    X& operator=(int) { std::cout << "operator=(int)\n"; return *this; }
    operator int() { return 0; }
};

int main()
{
    X a, b;
    a = b;
}

But he is not called. This is because it calls the implicit copy assignment operator, which is an exact match for the argument. I want my code to first call the conversion operator on b, and then return a value intfor operator=().

Is there any syntax to tell the compiler to "ignore this function"? In other words, how to remove a function from overload resolution?

-, SFINAE, , , - .

+4
3

, = delete , .. , . :

X& X::operator= (X const& other) {
    return (*this) = static_cast<int>(other);
}

, , :

T -> X -> int

, :

template <typename T>
X& X::operator= (T&& other) {
    int arg = other;
    return (*this) = arg;
}
+4

( , ).
++ Meyers Chapter 2, item 6.

0

Just write

a = static_cast<int>(b);
0
source

All Articles