以下(一般)情况:
我试图在类中调用另一个 constexpr
成员函数,但收到错误消息:'this' 不是常量表达式
。我现在的问题是(因为我是 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
并不意味着“这个函数只能在编译时调用”。这意味着“这个函数可以在编译时和运行时调用”。
char x=testM2<testM1<varbase>()>();
如果在运行时调用,则 this
的值不是编译时常量。因此 constexpr
方法调用的结果不是编译时值,因此其结果不能用作模板参数。
如果您没有使用this
(正如您似乎没有使用的那样),则将testM2
等标记为static
可以解决您的问题。如果您使用this
,那么没有简单的解决方法;没有办法说“这个函数只会在编译时调用”。任何解决方法都取决于您使用 this
执行的操作的详细信息以及返回值(如果可能的话)。添加这些详细信息编写一个新问题。
关于c++ - 对 constexpr 函数的嵌套调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51892904/