2

In the follwing example code I use the object a0 as a non-type template-parameter, which works well, because it is an object with linkage (lvalue-ref). So I thought it must be possible to do so with an array element, but that fails:

constexpr uint8_t a[10] = {};
constexpr uint8_t a0 = {};

template<typename T, const T& V>
struct Test {};

using test = Test<uint8_t, a0>; // OK
using test = Test<uint8_t, a[0]>; //NOK

Is there a way to get this working?

1 Answer 1

2

Binding a reference template parameter requires a name of an object with external linkage. Individual array elements have no name and no linkage in C++. This is why a reference template parameter cannot be bound to an array element. See 6.5 Program and linkage [basic.link] for full details.

You can make it compile if you drop the reference (if possible):

template<typename T, T V>
struct Test {};

Or access the element by index inside the template:

template<class T, T const& A, size_t Idx>
struct Test2 {
    static constexpr decltype(A[Idx]) element = A[Idx];
    static_assert(std::is_reference<decltype(element)>::value, "");
};

using test = Test2<decltype(a), a, 1>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.