C++ - Default arguments cannot be added to an out-of-line definition of a member of a class template
Asked Answered
D

2

10

I have an iOS app that makes use of a C++ class from MPL called 'square.h' and whenever I build the app Xcode throws this error -

Default arguments cannot be added to an out-of-line definition of a member of a class template

Now, my understanding of C++ syntax is very little, so what does this error mean?

The problematic line is below -

template <class T> 
TSquare<T>::TSquare (T size_, T x_, T y_, T scale_=0)
{
    size = size_;
    x = x_;
    y = y_;
    scale = scale_;
}
Debutante answered 3/9, 2014 at 14:40 Comment(0)
S
17

Default arguments are not part of the definition, only declaration:

template <class T>
class TSquare
{
public:
    TSquare (T size_, T x_, T y_, T scale_ = 0);
};

// out-of-line definition of a member of a class template:
template <class T>
TSquare<T>::TSquare (T size_, T x_, T y_, T scale_ /* = 0 */)
{

}

or:

template <class T>
class TSquare
{
public:
    // in-line definition of a member of a class template
    TSquare (T size_, T x_, T y_, T scale_ = 0)
    {

    }
};
Somite answered 3/9, 2014 at 14:41 Comment(0)
S
5

According to the standard (N3797) §8.3.6/6 Default arguments [dcl.fct.default] (emphasis mine):

Except for member functions of class templates, the default arguments in a member function definition that appears outside of the class definition are added to the set of default arguments provided by the member function declaration in the class definition. Default arguments for a member function of a class template shall be specified on the initial declaration of the member function within the class template.

The above means that default arguments for member functions of template classes go only inside the definition of the class. As such, you will either put in the declaration of the member function the default argument:

template<T>
class TSquare {
  ...
  TSquare (T size_, T x_, T y_, T scale_ = 0);
  ...
};

Or you shall put the entire definition of the member function inside the class definition.

template<T>
class TSquare {
  ...
  TSquare (T size_, T x_, T y_, T scale_ = 0) {
    ...
  }
  ...
};
Streptokinase answered 3/9, 2014 at 14:50 Comment(1)
I had been looking for answers to this issue since two days ago! Thanks!Debutante

© 2022 - 2024 — McMap. All rights reserved.