Search code examples
c++templates

How to get the value of a non-type template parameter?


Here is the example:

template <int n>
class A { };

class B {
public:
  int foo() {
    return a.n;  // error
  }
private:
  A<10> a;
};

I want to get the value of instantiated class A<10>'s non-type template parameter in class B other than template A itself, is there a way to do this? Or should I use some other designs to avoid this problem?


Solution

  • If you can't get the type to cooperate (by publishing the parameter value), you can extract it yourself with a traits class:

    template<class> struct A_param; // not defined
    
    template<int N> struct A_param<A<N>> {
        static constexpr int value = N;
    };
    
    // a more general implementation would probably want to handle cv-qualified As etc.
    

    Then use A_param<decltype(a)>::value.