简体   繁体   中英

C++ template with default parameters

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM