繁体   English   中英

带有 constexpr 的模板 function 调用返回 function 值 C++

[英]Template function call with constexpr return function value 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'
    }
};

在尝试从struct B调用somefunc f中的 somefunc 时,我收到一条错误消息,提示'this cannot be used in a constant expression.' 我要求的事情是不可能的吗?

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

是和不是。 this是一个运行时值,确实不能在常量表达式中使用。

但是在您的情况下,似乎mytype()不需要成为成员 function,因此您可以将其声明为static

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

现在它将起作用。 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM