使用模板重载函数

Overloading a function using templates

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

我正在尝试使用模板定义一个函数,并且我希望类型名称是int或anEnum(我定义的特定枚举(。我尝试了以下操作,但失败了:

template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}

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

isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)

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

除了非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;
}

演示

更新

根据@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;
}

有几种方法可以实现这一点。所有这些都涉及使用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> {
}

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

这个解决方案怎么样?如果类型T满足您的要求,则会编译带有该函数的代码。否则,静态断言失败。

#include <type_traits>
enum anEnum {
//
};
template <typename T, bool defined = std::is_same<T, int>::value ||
std::is_same<T, anEnum>::value>
bool isFunction(const T& aVariable)
{
static_assert(defined, "Invalid specialization");
bool result = false;
// Put your code here
return result;
}

我改进了https://stackoverflow.com/a/60271100/12894563回答。"如果constexpr在这种情况下可以提供帮助:

template <typename T>
struct always_false : std::false_type {};
template <typename T>
bool isFunction(const T& aVariable)
{
if constexpr(std::is_same_v<T, int> || std::is_same_v<T, anEnum>)
{
std::cout << "intn";
// put your code here
return true;
}
else
{
static_assert(always_false<T>::value, "You should declare non-template function or write if constexpr branch for your type");
return false;
}
}
bool isFunction(std::string_view)
{
std::cout << "std::string_viewn";
return true;
}
int main()
{
isFunction(std::string_view("1L"));
isFunction(1);
//isFunction(1L); // will produce an error message from static_assert
}

isFunction(1L(将失败,因为没有重载函数或"if constexpr"分支。

更新:修复了遗漏的

template <typename T>
struct always_false : std::false_type {};

https://godbolt.org/z/eh4pVn