简体   繁体   English

如何为两种或更多数据类型创建 function 模板?

[英]How can I create function templates for the two or more data types?

I want to use function templates with two or more data types.我想使用具有两种或多种数据类型的 function 模板。 So I made a example, which gets two 'T' type data then return 'T1' type data.所以我做了一个例子,它获取两个'T'类型数据然后返回'T1'类型数据。 Here is code:这是代码:

#include <iostream>
using namespace std;
template <typename T, typename T2> T get(T2 a, T2 b)
{
    if (a < b)
        return b;
    else
        return a;
}

int main()
{
    cout << get<float, int>(10.2, 20.3);
}

I want that this code returns the larger of the two 'int-type' numbers to the 'float' type.我希望这段代码将两个“int-type”数字中较大的一个返回到“float”类型。 Namely I expected the result to '20.0'.也就是说,我预计结果为“20.0”。 But the result is 20. I can not understand why the result's type is 'int'.但结果是 20。我不明白为什么结果的类型是 'int'。 Please correct my code to return 'float' type, '20.0'.请更正我的代码以返回“浮点”类型“20.0”。 Namely I wonder how to specify the data type of the return value if the input factor and return value are different.即我想知道如果输入因子和返回值不同,如何指定返回值的数据类型。

Your code is perfectly fine, given the strange cast of inputs to int .考虑到int输入的奇怪类型,您的代码非常好。 Look at the output of:看output的:

#include <iostream>
#include <boost/type_index.hpp>
using namespace std;
using boost::typeindex::type_id_with_cvr;

template <typename T, typename T2> T get(T2 a, T2 b)
{
    if (a < b)
        return b;
    else
        return a;
}

int main()
{
  float test = 20.0;
  
  cout << get<float, int>(10.2, 20.3) << " "
       << type_id_with_cvr<decltype(get<float,int>(10.2,20.3))>().pretty_name() << endl;
  cout << test << endl;
}

which is这是

20 float
20

so, of course, the return type of your function IS float, the output is just how cout will show this to you.所以,当然,你的 function 的返回类型是浮点数,output 就是 cout 将如何向你显示这个。 But you know, you can highly customize how cout prints out your data with #include <iomanip> .但是您知道,您可以使用#include <iomanip>高度自定义 cout 如何打印出您的数据。

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

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