简体   繁体   English

具有默认参数的C ++模板

[英]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 然后g ++ myadd.cpp

It shows error: 它显示错误:

default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x 没有-std = c ++ 0x或-std = gnu ++ 0x的函数模板中不得使用默认模板参数

Why does this happen? 为什么会这样?

I extracted this answer from Stack Overflow question Default template arguments for function templates : 我从函数功能模板的 Stack Overflow问题Default template arguments中提取了此答案:

To quote C++ Templates: The Complete Guide (page 207): 引用C ++模板:完整指南(第207页):

When templates were originally added to the C++ language, explicit function template arguments were not a valid construct. 最初将模板添加到C ++语言时,显式函数模板参数不是有效的构造。 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. 注意:函数模板C ++中的默认参数是gnu ++ 0x中的新功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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