您需要为接受两个结构元素参数并返回较大元素的值的函数创建显式模板特化。该元素的类型为 float。该程序还有一个函数模板,它接受任何类型(内置)的两个数字并返回其中较大的一个。我编写了代码,但是当我尝试为结构创建模板时,我收到一个我不明白的错误 - “没有函数模板的实例与指定的类型匹配”。我的问题的目的是了解为什么这不起作用,而不是用其他方式解决它。
#include <iostream>
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
template <typename Any>
Any grand_number(Any n, Any b);
template <>
float grand_number (box n, box b);
int main()
{
box one = { "Dmitry", 10, 10, 10,1000 };
box two = { "Dmitry", 10, 10, 10,1222 };
std::cout << grand_number(2, 69);
std::cout << grand_number(one,two);
return 0;
}
template <typename Any> Any grand_number(Any n, Any b)
{
return (n < b) ? b : n;
}
template <>
box grand_number<box>(box n, box b)
{
return (n.volume < b.volume) ? b.volume : n.volume;
}
好吧,您的模板仍然返回与传递的相同类型( pass
Any
, returnAny
)。你想传递一种类型 -box
,并返回另一种 -float
(一旦你写了float
,第二个 -box
。你需要更加小心:))其工作原理如下:
确实,这不是你想要的......
而且,尽管你不想听如何绕行,但我仍然会写:超载会拯救你。