Reputation: 965
I would like to ask about function overloading using SFINAE. I have defined 2 functions, one of which should be used when integral type is passed as parameter, other one should be used when floating point is passed as parameter. Here is code:
template <typename T, typename If<IsIntegral<T>::value,T>::Type = 0>
void function(T t) {
std::cout << "T is integral type" << std::endl;
}
template <typename T, typename If<IsReal<T>::value,T>::Type = 0>
void function(T t) {
std::cout << "T is real type" << std::endl;
}
This compiles fine. When I instantiate integral version of function, like this:
function(4);
function(28l);
it still works as it should (I get the message "T is integral type"). However, when I add another instance for floating point types:
function(4);
function(28l);
function(4.5f);
I get error saying, that there is no matching function to call to "function(float)". What is wrong with this snippet of code? By the way, the If template class is only an alias for enable_if.
Upvotes: 0
Views: 1890
Reputation: 275370
Well, you can't have a constant of type float
as a template parameter.
Try class=typename If<IsRead<T>::value,T>::Type
and similar in the other case as a first pass.
If you have C++11, try using
aliases to get rid of typename
spam. In addition, prefer std::enable_if<?>
to If<?>
when posting questions asking for help, because I had to guess what If
does (and for all I know, your real problem is in your implementation of If
and IsReal
etc).
Upvotes: 3