0

I try to use default parameters in my template, like this

#include <iostream>

using namespace std;

template <typename S, typename T=int> 
S myadd(T a, T b)
{
    S tmp = a + b;
    return tmp;
}

int main()
{
    int a = 1, b = 2;
    float i = 5.1, j = 5.2;

    cout << myadd<int, int>(i, j);
    cout << myadd<float>(a, b);

    return 0;
}

Then g++ myadd.cpp

It shows error:

default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x

Why does this happen?

Bart
  • 19,692
  • 7
  • 68
  • 77
Jeff Ma
  • 31
  • 2
  • 9

1 Answers1

1

I extracted this answer from Stack Overflow question Default template arguments for function templates:

To quote C++ Templates: The Complete Guide (page 207):

When templates were originally added to the C++ language, explicit function template arguments were not a valid construct. Function template arguments always had to be deducible from the call expression. As a result, there seemed to be no compelling reason to allow default function template arguments because the default would always be overridden by the deduced value.

Read the Stack Overflow question to understand quite more. NOTE: the default parameter in a function template C++ is a new feature in gnu++0x.

Community
  • 1
  • 1
Agus
  • 1,604
  • 2
  • 23
  • 48