c++templatesnon-type-template-parameter

Class specialization for array NTTP


I'm trying to specialize the template X for an array NTTP.

But this does not work:

template<auto& V>
struct X {
    static inline auto v = V[0];
};

template<typename T, auto N>
struct X<T (&a)[N] > {
    static inline auto v = N;
};

int main () {
    int ar[10];
    X<ar> x;
    return x.v;
}

Is that possible in the first place? Or should one use requirements / constraints for that purpose?

The errors are:

<source>:14:14: error: 'a' was not declared in this scope
   14 | struct X<T (&a)[N] > {
      |              ^
<source>: In function 'int main()':
<source>:20:9: error: the address of 'ar' is not a valid template argument because it does not have static storage duration
   20 |     X<ar> x;
      |         ^
<source>:21:14: error: request for member 'v' in 'x', which is of non-class type 'int'
   21 |     return x.v;
      |              ^
Compiler returned: 1

Solution

  • You have "typo" in the way to specialize (what is a)?

    The specialization should look like:

    template<typename T, std::size_t N, T (&a)[N]>
    struct X<a> {
        static inline auto v = N;
    };
    

    And ar should have the appropriate storage duration, as the error further indicates.

    Demo