对于多个函数使用相同的模板 [英] Use the same template for several functions
问题描述
如果需要使用相同模板的几个函数,是否有一种方法来声明和实现它们,而不必每次都声明模板?
If several functions which use the same template are needed, is there a way to declare and implement them without declaring the template each time?
template <typename T>
T mymax (T a, T b);
template <typename T>
T mymin (T a, T b);
template <typename T>
T myfoo (T a, T b);
/********************************************/
template <typename T>
T mymax (T a, T b) {
return (a > b ? a : b);
}
template <typename T>
T mymin (T a, T b) {
return (a < b ? a : b);
}
template <typename T>
T myfoo (T a, T b) {
return max(a,b)+min(a,b);
}
是否有办法写 ; typename T>
只有一次代码块?类似的东西:
Is there a way to write the line template <typename T>
just one time for a block of code? Something that will look like:
template <typename T> {
T mymax (T a, T b);
T mymin (T a, T b);
T myfoo (T a, T b);
}
(此代码不是合法的语法, p>
(this code isn't legal syntax and doesn't compile)
推荐答案
实现这样的东西的唯一方法是滥用结构和静态函数。不幸的是,您需要明确提及模板类型。
The only way to achieve something like this is to misuse a struct and static functions. Unfortunately, you'll need to explicitly mention the template type.
#include <iostream>
template<typename T>
struct my
{
static T max(T a, T b) { return (a > b ? a : b); }
static T min(T a, T b) { return (a < b ? a : b); }
static T foo(T a, T b) { return max(a, b) + min(a, b); }
};
现场演示。选择一个更好的类名。
Live Demo. Pick a better class name.
我不能想到任何更好的解决方案。只需写入 template< typename T>
。你会习惯它。它的目的,它真的不是你想象的丑陋。
I can't think any "better" solution. Just write the template<typename T>
. You'll get used to it. It serves a purpose, and it really isn't as ugly as you think.
这篇关于对于多个函数使用相同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!