lundi 20 juin 2016

Why default argument can't be added later in template functions?

C++ standard section 8.3.6.4 says that

For non-template functions, default arguments can be added in later declarations of a function in the same scope. [...]

But my question is that why it isn't allowed for template functions? What is the rationale for not allowing addition of default arguments in later declarations in same scope for template functions?

Consider this program which compiles fine. (non template function) (see live demo here.)

#include <iostream>

int f(int a,int b,int c=3);
int f(int a,int b=9,int c); // default argument in middle, ok allowed

int main()
{
    f(3);
    f(3,6);
    f(3,6,9);
    return 0;
}

int f(int a,int b,int c)
{
    std::cout<<a<<' '<<b<<' '<<c<<'n';
    return 0;
}

But following fails in compilation. (template function) (see live demo here.)

#include <iostream>

template <typename T> 
void f(T a,int b,int c=3);
template <typename T> 
void f(T a,int b=9,int c); // compiler error why???

int main()
{
    f(3);
    f(3,6);
    f(3,6,9);
    return 0;
}

template <typename T> 
void f(T a,int b,int c)
{
    std::cout<<a<<' '<<b<<' '<<c<<'n';
} 

Aucun commentaire:

Enregistrer un commentaire