在模板中,如果我们创建一个函数并通过引用传递变量address作为参数,它会给出所需的输出吗?

In templates if we create a function and pass variable address as parameters by reference will it give the required output

本文关键字:参数 变量 address 输出 引用 我们 创建 如果 函数 一个      更新时间:2023-10-16

下面给出的代码与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;
    }