Search code examples
c++11constexprstdarray

Can I use const & as parameter of a constexpr function?


I'm writing a constrexpr function taking either a CArray T(&)(N), either a std::array. I think I have to write 2 functions (if you know better I would be happy to know),

But I'm concerned about what I wrote with the std::array

    constexpr float LinInterp01(const std::array<float, N>& inArray, float inX);

Is it correct when writing a constrexpr function to pass by const & or not?

I think it should be because at compile time the compiler would instanciate a copy and there is no notion of L Value, at compile time.

Could someone explain me this?


Solution

  • C++ standard section § 7.1.5 [dcl.constexpr]

    The definition of a constexpr function shall satisfy the following constraints:

    — it shall not be virtual (10.3);

    — its return type shall be a literal type;

    — each of its parameter types shall be a literal type;

    And section § 3.9 [basic.types]

    A type is a literal type if it is:

    — void; or

    — a scalar type; or

    a reference type; or

    — an array of literal type; or

    — a class type (Clause 9) that has all of the following properties:

    — it has a trivial destructor,

    — it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor template that is not a copy or move constructor, and

    — all of its non-static data members and base classes are of non-volatile literal types.

    So yes, you can pass parameters by reference to constexpr functions.

    Now whether or not your function calls will actually be evaluated at compile time depends on the body and calls of LinInterp01.