Using typedef types in definition

Viewed 98

I have a class as follows,

template<size_t N>
class A 
{
   typedef int(*ARRAY)[N];
   array getArray();

   ARRAY array;
};

Then how can I use the type ARRAY in the definition? I have tried this

template<size_t N>
ARRAY A<N>::getArray()
{
   return array;
}

But, it tells me that ARRAY is not defined.

3 Answers

ARRAY is depended name, therefor you need to use the typename keyword before it, outside the class scope.

template<size_t N>
typename A<N>::ARRAY A<N>::getArray()
//^^^^^^^^^^^^^
{
   return array;
}

or using trailing return

template<size_t N>
auto A<N>::getArray() -> ARRAY
//                 ^^^^^^^^^^^^^
{
   return array;
}

In addition, you have a typo in your class member declaration. The

array getArray();

should be

ARRAY getArray();

However, is there any reason that you do not want to use the std::array?

The problems is that you haven't defined a type ARRAY in the namespace, but rather within the scope of the class template. As such, the unqualified lookup doesn't find a type by that name.

Besides using a qualified name to refer to this member type alias as shown in Bill Lynch's answer, another way is to use a trailing return type in which case the name is looked up within the context of the class:

template<size_t N>
auto A<N>::getArray() -> ARRAY {
    return array;
}

P.S. I recommend highly against obfuscating the pointerness (or referenceness) of types by defining type aliases unless the alias is used in generic programming where it might be replaced by a fancy pointer (or proxy reference). In such cases the alias should conventionally be named to signify that it is a "pointer" (or "reference") such as for example in the case of type aliases of iterators and allocators and their type traits in the standard library.

Related