Search code examples
c++type-conversionoperatorsimplicit-conversion

Deleting all lvalue conversion operators


I want to avoid all lvalue conversions from a type to another type:

struct A
{};

struct T
{
    A a;
    operator A() { return a; }
    //operator A&() = delete; how to delete lvalue conversions to A?
};

void bar(A)
{}

void foo(const A&)
{}

void foo2(A&)
{}

int main()
{
    T t;

    bar(t); // fine
    foo(t); // should never convert to ref-to-const A
    foo2(t); // should never convert to ref-to A

    return 0;
}

Is this possible? How and which conversion operators do I need to delete?

Example on godbolt


Solution

  • You might do

    struct T
    {
        A a;
        operator A() { return a; }
        
        template <typename T> operator const T&() = delete;
    };
    

    Demo