Home > Net >  Why this constexpr expression gives me an error?
Why this constexpr expression gives me an error?

Time:10-16

In the code below, constexpr for the line 2 does not give an error, but line 1 does.

#include <iostream>

using namespace std;

class ComplexNum{
public:constexpr ComplexNum(int _r=0,int _i=0):r(_r),i(_i){}
private:
     int r,i;

};

int randGen(){
return 10;
}
constexpr int numGen(int  i,int j){
return i j;
}
int main()
{
    
    constexpr int i=10,j=20;
    constexpr ComplexNum c3(randGen(),randGen());    //line 1
    constexpr ComplexNum c4(numGen(i,j),numGen(i,j));//line 2

   
    return 0;
}

From the knowledge I have, constexpr evaluates the expression at compile time.

Then, shouldn't the compiler be able to evaluate the expression in line 1, because it returns a constant integer (10 in this case)?. If not, how will line 2 be okay?

CodePudding user response:

The compiler can't compile line one because randGen() is not constexpr. The compiler can't magically tell if a function is constexpr. Maybe it looks constexpr, but you actually want it to run at runtime. For that reason, the compiler doesn't evaluate expressions which are not marked constexpr explicitly. Do this:

#include <iostream>

using namespace std;

class ComplexNum{
public:constexpr ComplexNum(int _r=0,int _i=0):r(_r),i(_i){}
private:
     int r,i;

};

constexpr int randGen(){
return 10;
}
constexpr int numGen(int  i,int j){
return i j;
}
int main()
{
    
    constexpr int i=10,j=20;
    constexpr ComplexNum c3(randGen(),randGen());    //line 1
    constexpr ComplexNum c4(numGen(i,j),numGen(i,j));//line 2

   
    return 0;
}
  •  Tags:  
  • c
  • Related