Deleting all lvalue conversion operators

馋奶兔 提交于 2021-02-18 12:55:08

问题


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


回答1:


You might do

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

Demo



来源:https://stackoverflow.com/questions/66153505/deleting-all-lvalue-conversion-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!