简体   繁体   English

C ++中的模板变量

[英]Template variables in C++

I have this code: 我有这个代码:

template <class T>
T GetMax (T a, T b) {
  return (a>b?a:b);
}


int main () {
  int i=51, j=26, k;
  long l=100, m=15, n;
  k=GetMax(i,j);
  n=GetMax(l,m);
  cout << k << endl;
  cout << n << endl;
  return 0;
}

How can I change the data type of variables k and n so that they can be dynamic enough to accept the returned value. 如何更改变量k和n的数据类型,以便它们足够动态以接受返回的值。 If the returned value is a double, the k and n will automatically be double, so I need not bother whether I am passing in int or double. 如果返回的值是double,则k和n将自动加倍,所以我无需担心我是传递int还是double。

I tried searching it in online and in my books but no luck. 我尝试在网上和书中搜索但没有运气。 Can you Plz help me? 你能帮助我吗? I am new to templates. 我是模板的新手。

In C++11, you can use auto : 在C ++ 11中,您可以使用auto

auto k = GetMax(i,j);
auto n = GetMax(l,m);

The types of k and n are deduced from the expression used to initialise them. kn的类型是从用于初始化它们的表达式推导出来的。

Prior to C++11, you would need to give the types explicitly. 在C ++ 11之前,您需要明确地给出类型。 However, you should always be able to write the types in some form or another, since you know the types of the arguments. 但是,您应始终能够以某种形式编写类型,因为您知道参数的类型。

You can't but you don't need to. 你不能,但你不需要。

GetMax will always be called in the context where you know what types you passed in, so you know what the return type could be. GetMax将始终在您知道传入的类型的上下文中被调用,因此您知道返回类型可能是什么。

For example, if you pass in two ints, the result will be int. 例如,如果传入两个整数,则结果为int。 If you pass in a double and a long, it will be a double. 如果你传入一个双倍和一个长,它将是一个双倍。

Think of templates as type safe macros. 将模板视为类型安全宏。 Replace the call of the function by the body of the function with the types replaced and that's what it will do. 用替换的类型替换函数体的函数调用,这就是它将要执行的操作。

You could use reference to make compiler warn you if you don't behave. 如果你不表现,你可以使用引用让编译器发出警告。

template <class T>
void GetMax (T a, T b, T& output) {
  output = (a>b?a:b);
}

But if you can use C++11, use auto instead. 但是,如果您可以使用C ++ 11,请使用auto

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM