使用constexpr返回函数值C ++的模板函数调用

问题描述

这是我的代码

enum class MYENUM {
A = 0,B = 1
};

template<MYENUM T>
void somefunc() {
    std::cout << "working" << std::endl;
}
struct A {
    constexpr MYENUM mytype() {
        return MYENUM::A;
    }
};
struct B {
    A obj;
    void f() {
        somefunc<obj.mytype()>(); //'this cannot be used in a constant expression'
    }
};

尝试从somefunc函数f调用struct B时,我收到一条错误消息,说'this cannot be used in a constant expression.'是我所要求做的事吗?

解决方法

我要求做的是不可能的事吗?

是,不是。 this是运行时值,实际上不能在常量表达式中使用。

但是在您的情况下,似乎mytype()不必是成员函数,因此可以声明为static

struct A {
    static constexpr MYENUM mytype() {
        return MYENUM::A;
    }
};

现在它可以工作了。 (Demo