Jack
Jack

Reputation: 384

Public Access of Template Value

Consider the following:

template<int T>
class Test {
public:
    constexpr static int A = T;
};

int main(int argsc, char** args) {
    std::cout << Test<2>::T << std::endl; // Option 1
    std::cout << Test<2>::A << std::endl; // Option 2
}

Why doesn't option 1 compile? It seems that the static constexpr A is just an extra step. Is it that T isn't available publicly?

Is there a cleaner way to get at T than by creating a publicly accessible member like A above?

Upvotes: 0

Views: 51

Answers (1)

Barry
Barry

Reputation: 303387

Why doesn't option 1 compile?

Because a template parameter is just the name of a parameter. You're allowed to rename them, that is:

template <class T> struct X;

// refers to same X
template <class U> struct X { ... };

// still the same X
template <class V>
void X<V>::foo() { ... };

For the same reason that you're allowed to name your function parameters differently between the declaration and definition. Requiring the name of the template parameter to be automatically visible within the class template would mean it would have to be fixed at first go.

Is there a cleaner way to get at T than by creating a publicly accessible member like A above?

Creating the publicly accessible member is usually the way to go. Alternatively, you can create an external trait:

template <class T> struct X { using type = T; }; // internal

template <class > struct get_type;
template <class T> struct get_type<X<T>> { using type = T; }; // external

Upvotes: 2

Related Questions