这是我的代码:
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.'
是我要执行的操作吗?
最佳答案
Is what I am asking for impossible to do?
是的,没有。
this
是运行时值,实际上不能在常量表达式中使用。但是在您的情况下,
mytype()
似乎不需要成为成员函数,因此可以将其声明为static
。struct A {
static constexpr MYENUM mytype() {
return MYENUM::A;
}
};
现在它将起作用。 (Demo)
关于c++ - 使用constexpr返回函数值C++的模板函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63522187/