对多个函数使用相同的模板

Use the same template for several functions

本文关键字:函数      更新时间:2023-10-16

如果需要多个使用相同模板的函数,有没有一种方法可以在每次都不声明模板的情况下声明和实现它们?

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);
}

有没有一种方法可以为一个代码块只写一次template <typename T>行?看起来像:

template <typename T> {
  T mymax (T a, T b);
  T mymin (T a, T b);
  T myfoo (T a, T b);
}

(此代码不是合法语法,无法编译)

实现这种功能的唯一方法是滥用结构和静态函数。不幸的是,您需要明确提及模板类型。

#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); }
};

现场演示。选择一个更好的类名。

我想不出任何"更好"的解决方案。只需编写template<typename T>。你会习惯的。它是有目的的,它真的没有你想象的那么丑陋。

有一个选项可以缩短代码,但它实际上与您所要求的完全相反:您可以省略template<...>-部分,但可以简化其余部分:

// create a shortcut for the function type
template<typename T>
using my = T( T a, T b );
// declare several functions with an identical signature
template<typename T> my<T> mymin;
template<typename T> my<T> mymax;
template<typename T> my<T> myfoo;

请注意,这仅适用于声明,定义将不会从中受益。

实时示例