【发布时间】:2019-01-24 08:23:38
【问题描述】:
以下(一般)情况:
我试图在一个类中调用另一个constexpr 成员函数,但我得到'this' is not a constant expression 的错误。我现在的问题是(因为我是 constexpr 成语的新手),如果不允许这样的用例。不然怎么解决?
#include <iostream>
class cc
{
public:
cc()=default;
~cc()=default;
// public method to call th eprivate constexpr functions
template<int varbase>
constexpr void doSomething()
{
static_assert(varbase>0, "varbase has to be greater zero");
// nested call to constexpr functions
char x=testM2<testM1<varbase>()>();
}
private:
template<int var1>
constexpr int testM1()
{
int temp=var1;
return (++temp);
}
template<int var2>
constexpr char testM2()
{
int temp=var2;
if (temp==2)
return 'A';
else
return 'B';
}
};
int main()
{
cc obj;
obj.doSomething<1>();
return 0;
}
【问题讨论】:
-
constexpr函数可以在非constexpr上下文中调用。我怀疑它们不能用作模板参数。 -
只需将
testM1和testM2标记为static。你想要做的就像constexpr void foo(int i) { std::array<int, i> arr; }。这是不允许的。 -
问题是
cc的每个实例都有自己的doSomething()、testM1()和testM2()版本。为了解决这个问题,编译器将在所有函数前面应用this,以识别您尝试引用的cc的哪个实例。this不是常量表达式。它在运行时进行评估。要解决此问题,请将您的constexpr函数移到类外,或将这些函数标记为static。
标签: c++ c++11 nested c++14 constexpr