Quantcast
Channel: Overloading a function using templates - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by NutCracker for Overloading a function using templates

$
0
0

In addition to non-C++20 answer, if you are, by any chance, able to use C++20 and its concepts feature, I would suggest you the following implementation:

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

Demo

UPDATE

According to @RichardSmith's comment, here is a more scalable and reusable approach:

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

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>