0

How do I create a nested template struct implementration? For example, if I have:

foo.h:
template<class T>
class foo
{
    template<class U>
    struct bar
    {
        U u;
        bar(U u);
        ...
    };
    ...
};

and

foo.cpp
include "foo.h"
...
template<class T, class U>
foo<T>::bar<U>::bar(U u) : u(u) { }
...

I get different syntax errors such as "missing ';'", etc. What am I doing wrong?

  • 2
    Templates are header only. So no cop file. If you want to implement in cop file, you need to instantiate them in the header. – Oblivion Nov 17 '19 at 20:04

2 Answers2

3

There are three issues in your code:

  1. You do miss semicolons as error message suggests

class definition must be followed by a semicolon:

template<class T>
class foo
{
    template<class U>
    struct bar
    {
        U u;
        bar();
        ...
    };
// ~~^ here
    ...
};
// ^ and here
  1. Class foo<T>::bar<U> has no constructor which takes 1 parameter. Either change your definition or implementation.

  2. template clauses are not mergeable. If you needed 2 template keywords, you still need 2 of them anywhere else:

Like this:

template<class T>
template<class U>
foo<T>::bar<U>::bar(U u) : u(u) { }
  1. Maybe not really an issue, because we don't see your full code, but please read Why can templates only be implemented in the header file? before you proceed.
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • Oh, I really missed a semicolon here, in the example, but it's not missing in the real code (and consructor params too). What did I really miss were separate template keywords. By the way: is including an implementation file in a header considered bad practice? – EvilCasual Nov 17 '19 at 20:42
  • @EvilCasual It's explained in the question linked, and it's one of the solutions. Though I wouldn't call this file `Foo.cpp`, but rather something like `Foo.tpp`, to make it more clear why we include a non `.hpp` at the end of a `.hpp` file. – Yksisarvinen Nov 17 '19 at 21:10
1

It should be

template<class T>
template<class U>
foo<T>::bar<U>::bar(U u) : u(u) { }
Evg
  • 25,259
  • 5
  • 41
  • 83