Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 向模板传递参数_C++_Templates - Fatal编程技术网

C++ 向模板传递参数

C++ 向模板传递参数,c++,templates,C++,Templates,我有这个模板: template<class a> a multiply(a x, a y){ return x*y; } 模板 乘法运算(x,y){ 返回x*y; } 如何传递不同类型的参数?(例如int和float)只需像往常一样调用函数: int x = 2; int y = 3; multiply(x,y); 只需像往常一样调用函数: int x = 2; int y = 3; multiply(x,y); 这取决于你想要实现什么。您可

我有这个模板:

template<class a>
    a multiply(a x, a y){
        return x*y;
    }
模板
乘法运算(x,y){
返回x*y;
}

如何传递不同类型的参数?(例如int和float)

只需像往常一样调用函数:

int x = 2;
int y = 3;
multiply(x,y);

只需像往常一样调用函数:

int x = 2;
int y = 3;
multiply(x,y);

这取决于你想要实现什么。您可以显式地指定模板参数(而不是让它被推导),这将导致“不匹配”参数转换为该类型

这个答案中的所有例子都假设
inti;浮动f

例如,您可以执行以下操作:

float res = multiply<float>(i, f);  //i will be implicitly converted to float
float res=乘法(i,f)//我将隐式转换为float
或者这个:

int res = multiply<int>(i, f);  //f will be implicitly converted to int
int res=multiply(i,f)//f将隐式转换为int
甚至这个:

double res = multiply<double>(i, f);  //both i and f will be implicitly converted to double
double res=乘(i,f)//i和f都将隐式转换为double
如果确实希望接受不同类型的参数,则需要以某种方式处理返回类型规范。这可能是最自然的方法:

template <class Lhs, class Rhs>
auto multiply(Lhs x, Rhs y) -> decltype(x * y)
{
  return x * y;
}
模板
自动乘法(左x,右y)->十进制(x*y)
{
返回x*y;
}

这取决于您想要实现的目标。您可以显式地指定模板参数(而不是让它被推导),这将导致“不匹配”参数转换为该类型

这个答案中的所有例子都假设
inti;浮动f

例如,您可以执行以下操作:

float res = multiply<float>(i, f);  //i will be implicitly converted to float
float res=乘法(i,f)//我将隐式转换为float
或者这个:

int res = multiply<int>(i, f);  //f will be implicitly converted to int
int res=multiply(i,f)//f将隐式转换为int
甚至这个:

double res = multiply<double>(i, f);  //both i and f will be implicitly converted to double
double res=乘(i,f)//i和f都将隐式转换为double
如果确实希望接受不同类型的参数,则需要以某种方式处理返回类型规范。这可能是最自然的方法:

template <class Lhs, class Rhs>
auto multiply(Lhs x, Rhs y) -> decltype(x * y)
{
  return x * y;
}
模板
自动乘法(左x,右y)->十进制(x*y)
{
返回x*y;
}

使用您提供的模板,您无法传递不同的类型。使用您提供的模板,您无法传递不同的类型。我认为他希望将函数调用为
multiply(5,4.4f)
例如。我认为他希望将函数调用为
multiply(5,4.4f)
例如。在C++11之后,我们可以将签名更改为
auto multiply(Lhs x,Rhs y)
decltype(auto)multiply(Lhs x,Rhs y)
在C++11之后,我们可以将签名更改为
auto multiply(Lhs x,Rhs y)
decltype(auto)multiply(Lhs x,Rhs y)