October 22, 2024
Chicago 12, Melborne City, USA
templates

Syntax restriction on constructors of template classes


When I define a templace class, I can write this (as less <T> as possible):

template <typename T>
class Foo
{
  public:
    Foo(){}
    Foo(Foo const&){}
    ~Foo(){}
};

Or this (as many <T> as possible):

template <typename T>
class Foo
{
  public:
    Foo<T>(){}
    Foo<T>(Foo<T> const&){}
    ~Foo<T>(){}
};

When I define the functions of the class, I can write this (less) :

template <typename T> Foo<T>::Foo() {}
template <typename T> Foo<T>::Foo(Foo const&) {}
template <typename T> Foo<T>::~Foo() {}

Or this (more) :

template <typename T> Foo<T>::Foo() {}
template <typename T> Foo<T>::Foo(Foo<T> const&) {}
template <typename T> Foo<T>::~Foo<T>() {} // Yes, even that

But I can’t write this :

template <typename T> Foo<T>::Foo<T>() {}
template <typename T> Foo<T>::Foo<T>(Foo<T> const&) {}

The error (from gcc 13.2) is the following :

error: 'Foo<T>::Foo' names the constructor, not the type
error: and 'Foo<T>' has no template constructors

I don’t understand this restriction. What is the reason ? And why only for the definition ?

Example here.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video