2016-12-30 124 views
0

我有这样的模板:将参数传递给模板

template<class a> 
    a multiply(a x, a y){ 
     return x*y; 
    } 

我如何可以通过不同类型的参数? (int和float例如)

+2

使用您提供的模板,您无法传递不同的类型。 – DeiDei

回答

1

只是调用该函数像往常一样:

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

我想他想把这个函数称为'multiply(5,4.4f)',例如。 – DeiDei

5

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

在这个答案所有例子int i; float f;

例如,你可以这样做:

float res = multiply<float>(i, f); //i will be implicitly converted to float 

或者这样:

int res = multiply<int>(i, f); //f will be implicitly converted to int 

甚至这样的:

double res = multiply<double>(i, f); //both i and f will be implicitly converted to double 

如果您确实想接受不同类型的参数,则需要以某种方式处理返回类型规范。这可能是最自然的做法:

template <class Lhs, class Rhs> 
auto multiply(Lhs x, Rhs y) -> decltype(x * y) 
{ 
    return x * y; 
} 
+1

在C++ 11之后,我们可以将签名更改为“自动乘法(Lhs x,Rhs y)”或“decltype(自动)乘法(Lhs x,Rhs y)” – AndyG