1

This question seems very closely related to the following, yet I do not fully understand it yet.


I want to have a template class that does something non-trivial in the constructor, depending on another template type. A minimal example would be this here:

template <typename A>
class Class {
  public:
    template <typename B>
    Class();

  private:
    int i;
};

template <typename A, typename B>
Class<A>::Class() {
    B b;

    i = b.get_number();
}

That does not compile with GCC:

$ env LC_ALL=C g++ --std=c++11 -c template.cpp 
template.cpp:14:1: error: prototype for 'Class<A>::Class()' does not match any in class 'Class<A>'
 Class<A>::Class() {
 ^~~~~~~~
template.cpp:7:5: error: candidate is: template<class A> template<class B> Class<A>::Class()
     Class();
     ^~~~~

Compiling with Clang gives other errors:

$ env LC_ALL=C clang++ --std=c++11 -c template.cpp 
template.cpp:13:1: error: too many template parameters in template redeclaration
template <typename A, typename B>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template.cpp:3:1: note: previous template declaration is here
template <typename A>
^~~~~~~~~~~~~~~~~~~~~
1 error generated.

I can get it to compile when I attach the template parameter B to the whole class.

template <typename A, typename B>
class Class {
  public:
    Class();

  private:
    int i;
};

template <typename A, typename B>
Class<A, B>::Class() {
    B b;

    i = b.get_number();
}

Is there any way to contain the influence of template parameter B to the constructor? Or would I have to attach it to the whole class?

Community
  • 1
  • 1
Martin Ueding
  • 8,245
  • 6
  • 46
  • 92
  • 1
    What is the point of such a constructor? You can never invoke it. – Barry Feb 27 '17 at 17:05
  • @Barry: That is now my follow-up question. I get a syntax error at `Class c;`. So I need to inject some dummy variable in order to get the type deduced correctly? – Martin Ueding Feb 27 '17 at 17:12
  • @MartinUeding A question asked and answered in one of the questions you linked. – Barry Feb 27 '17 at 17:13

1 Answers1

6

The correct syntax for the out-of-class definition of a template method in a template class is as follows:

template <typename A> // Class template parameters
template <typename B> // Method template parameters
Class<A>::Class() { 
//   ^^^
//   Class template parameters

    // ...
}

live example on wandbox

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416