3

I am using c++ templates and created a template class inside a template class.

the situation is like this:

template <typename T>
class C {
    public:
    class N {
        T v;
    };

    template <typename D>
    N *fun(D d);
};

template <typename T>
template <typename D>
N *C<T>::fun(D d) {
}

int main() {
    C<int> obj;
    obj.fun('c');
}

Now compiler is giving error as:

main.cpp:14:1: error: ‘N’ does not name a type

If I use the function prototype outside class as C<T>::N *C<T>::fun(D d), compiler gives error:

main.cpp:14:1: error: need ‘typename’ before ‘C::N’ because ‘C’ is a dependent scope

If I define definition inside the class then it works fine. But I don't want to make it inline, how should I do it?

mrazimi
  • 311
  • 3
  • 11
Alok
  • 79
  • 1
  • 6

2 Answers2

6

As the compile error suggests, use typename

template <typename T>
template <typename D>
typename C<T>::N *C<T>::fun(D d) {
}
eike
  • 969
  • 5
  • 17
  • 2
    better don't refer to comments. They can go at any time. If your intention was to give credits, thanks, but credits should go to the one who writes the answer, while I should feel bad for giving away parts of the answer in a comment ;) – 463035818_is_not_a_number Sep 17 '19 at 08:38
1

As alternative, you might use trailing return type:

template <typename T>
template <typename D>
auto C<T>::fun(D d) -> N*
{
    return nullptr;
}
Jarod42
  • 173,454
  • 13
  • 146
  • 250