Error al mezclar la función de plantilla con el argumento predeterminado

I have a templated class and I'm having some issues. I have this intruction in another class:

value.push_back(x);

Being x a unsigned int, value the templated class which is called List<unsigned int>, and push_back this function:

template <class T>
void List<T>::push_back(T a=T(),int l=1){
    (*this).resize((*this).size+l,a);
}

And I have the following error in codeblocks:

...\mp.h|86|error: no matching function for call to 'List<unsigned int>::push_back(unsigned int)'
...\mp.h|86|note: candidate is:
...\list.h|36|note: void List<T>::push_back(T, int) [with T = unsigned int]
...\list.h|36|note:   candidate expects 2 arguments, 1 provided

I have no ideia what to do, the function has already a default value for int, and I've already tried with 2 different compilers, I really don't want to add the other argument in the push_back para que se convierta push_back(x,1).

preguntado el 22 de septiembre de 13 a las 20:09

1 Respuestas

Did you include the default value on the declaración?

template <class T>
struct List 
{
    void push_back(T a=T(),int l=1);
};

A good compiler should have refused to compile it if you didn't (or at least prevenido about the discrepancy), but, just to be sure.

it's customary to "just" implement template members in-class:

template <class T>
struct List 
{
    void push_back(T a=T(),int l=1)
    {
        (*this).resize((*this).size+l,a);
    }
};

Respondido el 22 de Septiembre de 13 a las 21:09

I just did what you say and sort of worked, I get another error which I think it hasn't to do with this issue. What I can't understand is why the default argument works without being also in the declaration without the function being templated and why it can be just in the declaration when it's templated. - user2054583

I can't tell for sure. But the issue seemed to be merely that, at time of invocation, the default argument value wasn't available to the compiler (which consequently didn't 'add' it). Default arguments are a call-site syntactic sugar only. This is a frequent source of confusion. You might want to side step all the confusion by using separate overloads instead. - seje

@user2054583 Well the Standard clearly forbids it in [dcl.fct.default]/6 "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." I can only guess this has to do either with instantiation or simplification (consider specializations). - Dyp

@DyP I was thinking the same. Or compiler malfunction. - seje

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.