c++ - 使用模板参数定义的两个不同参数首字母创建函数是否错误

标签 c++

根据我对模板的理解,

template<class it>
foo(it num1, it num2)  //both it forms int 
{
    num1=30;
    num2=20;

    cout<<num1<<endl;
    cout<<num2<<endl;

}

int main()
{
    int num1, num2;
    foo(num1,num2)
    return 0;
}

如果我希望函数参数的一侧是字符串,而函数参数的另一侧是 int 怎么办

template<class it>
foo(it num1, it alp)  //both it on left int, it on right string , if i had declared
                      // it on right as "string" instead of "it", it works just fine. 
{
    num1=30;
    alp="Name";

    cout<<num1<<endl;
    cout<<num2<<endl;  

}

int main()
{
    int num1; string alp; 
    foo(num1,alp)
    return 0;
}

模板是通用的,可以让您放置任何数据类型吗?如果是这样,我的程序不应该是合法的吗?

最佳答案

If so, shouldn't my program be legal?

没有。简单的说,你可以把模板参数it看成是一个类型的占位符。但是 itboth 参数的类型,所以你最终会得到 foo(int,int)foo(字符串,字符串)。相反,使用第二个模板参数:

template<class T, class U>
foo(T num1, U alp)
{
    num1=30;
    alp="Name";

    cout<<num1<<endl;
    cout<<alp<<endl;  
}

关于c++ - 使用模板参数定义的两个不同参数首字母创建函数是否错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23142178/

相关文章:

c++ - 使用最小值和最大值缩放 Mat 中的每个单元格

c++ - 如何根据 bool 值保存具有不同扩展名的文件

c++ - 如何让我的系统支持纳秒精度

c++ - 套接字发送数据但 recv 程序不能正常工作

c++ - winsock编译错误,找不到addrinfo结构和一些相关函数

c++ - 如何创建返回类型为 1) true/false 和 2) 动态数据的对象

c++ - Valgrind 报告 "Invalid free()/delete/delete[]"

c++ - 如何编译 CLOGS 库

c++ - 如何在 kd-tree 中表示线段

c++ - SDL2 FillRect 与 SDL_Window 问题