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

Answer by ixjxk for Overloading a function using templates

$
0
0

I've improved https://stackoverflow.com/a/60271100/12894563 answer. 'If constexpr' can help in this situation:

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 << "int\n";        // 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_view\n";    return true;}int main(){    isFunction(std::string_view("1L"));    isFunction(1);    //isFunction(1L); // will produce an error message from static_assert}

isFunction(1L) will fail becuase there is no overloaded function or 'if constexpr' branch.

UPDATE:Fixed missed

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

https://godbolt.org/z/eh4pVn


Viewing all articles
Browse latest Browse all 5

Trending Articles



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