使用模板重载函数

b.g*_*.g. 33 c++ templates overloading

我正在尝试使用模板定义一个函数,并且我希望 typename 为 int 或 anEnum(我定义的特定枚举)。我尝试了以下方法,但失败了:

template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}
Run Code Online (Sandbox Code Playgroud)

我想做的是使用模板,而不是定义两个重载函数。我更喜欢按如下方式调用函数,而程序员不必考虑类型

isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)
Run Code Online (Sandbox Code Playgroud)

基本上,我希望这个函数被模板化为 int 和 aNum 类型。我已经搜索过这个,但找不到答案。我可能缺少什么?谢谢,

Nut*_*ker 24

除了非 C++20 答案之外,如果您有机会使用C++20及其concepts功能,我建议您使用以下实现:

#include <iostream>
#include <concepts>

enum class MyEnum {
    A,
    B,
    C
};

template <typename T>
concept IntegralOrEnum = std::same_as<MyEnum, T> || std::integral<T>;

template <IntegralOrEnum T>
bool isFunction(T const& aVariable) {
    return true;
}

int main() {
    isFunction(MyEnum::A);
    isFunction(3);
    isFunction("my_string"); // error
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

演示

更新

根据@RichardSmith的评论,这是一种更具可扩展性和可重用性的方法:

template <typename T, typename ...U>
concept one_of = (std::is_same_v<T, U> || ...);

template <one_of<int, MyEnum> T>
bool isFunction(T const& aVariable) {
    return true;
}
Run Code Online (Sandbox Code Playgroud)


Sto*_*ica 21

有几种方法可以实现这一点。所有都涉及使用type_traits标题。例如,您可以对函数主体中的相关类型进行静态断言。

或者,如果您需要在其他重载中考虑此函数,则可以采用 SFINAE 技术。

template<typename T>
auto isFunction(const T &aVariable) 
  -> std::enable_if_t<std::is_same<T, int>::value || std::is_same<T,anEnum>::value, bool> {
}
Run Code Online (Sandbox Code Playgroud)

如果类型不匹配,这将在调用之前从重载集中删除该函数。但是,如果您不需要这种行为,静态断言确实允许提供对程序员更友好的错误消息。