带默认参数的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;
}
然后g ++ myadd.cpp
Then g++ myadd.cpp
它显示错误:
默认模板参数不能在函数模板中使用-std = c ++ 0x或 - 为什么会发生这种情况?
default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x
推荐答案
$ b解决方案
我从Stack中提取了此答案溢出问题 功能模板的默认模板参数 :
I extracted this answer from Stack Overflow question Default template arguments for function templates:
引用C ++范本:完整指南(第207页):
To quote C++ Templates: The Complete Guide (page 207):
当模板最初添加到C ++语言时,显式
函数模板参数不是有效的构造。函数
模板参数总是必须从调用
表达式中推导出来。结果,似乎没有令人信服的理由
允许默认的函数模板参数,因为默认值
总是被推导的值覆盖。
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.
阅读 Stack Overflow问题以了解更多信息。注意:函数模板中的默认参数C ++是gnu ++ 0x中的一个新功能。
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 ++模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!