Rumah > Artikel > pembangunan bahagian belakang > Mengapa Saya Tidak Boleh Menyalurkan Hujah Bukan Constexpr kepada Fungsi Constexpr?
Limitations of Constexpr Function Parameters in Constant Expressions
Consider the code snippet:
static constexpr int make_const(const int i){ return i; } void t1(const int i) { constexpr int ii = make_const(i); // error occurs here (i is not a constant expression) std::cout<<ii; }
Error Details
The code triggers an error when attempting to initialize ii with make_const(i) because i is not a constant expression. This is because:
Passing a non-constexpr parameter to a constexpr function does not result in a constexpr output. However, the constexpr function can inherit and propagate the constexprness of its input parameters.
Allowed Scenarios
The following code works because both t1() and make_const() are constexpr functions with constexpr parameters:
constexpr int t1(const int i) { return make_const(i); }
Limitations
The following code fails because do_something() is not a constexpr function, even though make_const() is:
template<int i> constexpr bool do_something(){ return i; } constexpr int t1(const int i) { return do_something<make_const(i)>(); // error occurs here (i is not a constant expression) }
Conclusion
Understanding the distinction between constexpr functions and variables is crucial to avoid such errors. Constexpr functions offer the flexibility of being evaluated at both compile-time and run-time, but only with constexpr arguments.
Atas ialah kandungan terperinci Mengapa Saya Tidak Boleh Menyalurkan Hujah Bukan Constexpr kepada Fungsi Constexpr?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!