Currently I'm reading Scott Meyers' Effective Modern C++ (Item 15 - Use constexpr whenever possible.). Author says:
When a constexpr function is called with one or more values that are not known during compilation, it acts like a normal function, computing its result at runtime. This means you don’t need two functions to perform the same operation, one for compile-time constants and one for all other values. The constexpr function does it all.
I've tried the following code snippet in http://ift.tt/1c5pPp7
#include <iostream>
class Point
{
public:
constexpr Point(double a, double b) noexcept
: _a(a), _b(b)
{
}
void print() const noexcept
{
std::cout << "a -> " << _a << "\tb -> " << _b << std::endl;
}
private:
double _a;
double _b;
};
double get_a() noexcept
{
return 5.5;
}
double get_b() noexcept
{
return 5.6;
}
int main()
{
constexpr Point p1(2.3, 4.4);
p1.print();
int a = get_a();
int b = get_b();
constexpr Point p2(a, b);
p2.print();
return 0;
}
In case of creating p1 object all goes as expected: arguments are known compile time and members are initialized properly. In case of creating p2 object, although we don't know the values of a and b variables at compile time, it should have worked in my understanding, because the constructor should have acted as a normal function. But I'm getting the following error messages:
main.cpp: In function 'int main()'
main.cpp:38:28: error: the value of 'a' is not usable in a constant expression
constexpr Point p2(a, b);
^
main.cpp:36:9: note: 'int a' is not const
int a = get_a();
^
main.cpp:38:28: error: the value of 'b' is not usable in a constant expression
constexpr Point p2(a, b);
^
main.cpp:37:9: note: 'int b' is not const
int b = get_b();
Coliru uses gcc compiler. So, I don't understand what is the problem. Maybe I've missed something...
Aucun commentaire:
Enregistrer un commentaire