在模板中,如果我们创建一个函数并通过引用传递变量address作为参数,它会给出所需的输出吗?
In templates if we create a function and pass variable address as parameters by reference will it give the required output
下面给出的代码与c++中的模板概念有关。我没有得到一个适当的结果,而传递变量。我期望的输出是交换的数字。但是,编译器显示错误。
#include<iostream>
using namespace std;
template <class T>
void swap(T& a,T& b)
{
T temp;
temp=a;
a=b;b=temp;
}
int main()
{
int a1,b1;
cin>>a1>>b1;
swap(a1,b1);
cout<<a1<<endl<<b1<<endl;
}
去掉'using namespace std;',因为在std中已经定义了命名空间交换函数模板。
另一个解决方案是可以专门化交换。但是您只能为用户定义的类型专门化标准函数
#include<iostream>
using namespace std;
struct Int
{
int i;
};
namespace std{
template <>
void swap<Int>(Int& a,Int& b)
{
Int temp;
temp=a;
a=b;b=temp;
}
}
int main()
{
Int a1,b1;
std::cin>>a1.i>>b1.i;
swap(a1,b1);
std::cout<<a1.i<<std::endl<<b1.i<<std::endl;
}
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- 扩展可变参数模板中的变量名称
- 在类构造函数中定义结构变量的参数
- 带有整数的变量参数列表
- 转发变量参数列表以模拟 std::thread
- 如何在不传递命令行参数的情况下在 c++ 中设置环境变量
- 存储稍后要转发的变量参数
- C++具有模板成员变量的类. 和参数内存输出
- 我应该如何在没有变量的情况下将相同的参数传递给 CMAKE 中的多个目标?
- 为变量模板的每个参数调用模板函数
- 具有推导参数的模板函数指针数组变量
- 函数参数变量总是需要 & 或 * 运算符吗?
- 为什么 beginthreadex 线程参数变量在父线程中没有更新
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 如何在函数中使用非参数变量?
- 即将将引用作为函数中的参数传递以更改参数变量的值
- 基于不断变化的参数/变量的XML get值
- cocos2d-x v3 CallFunc作为参数/变量如何
- 在编译时使用c++元编程中的运行时参数(变量)
- 我可以返回一个非参数变量吗?