How do I use std::enable_if with a self-deducing return type?

Viewed 10387

C++14 will have functions whose return type can be deduced based on the return value.

auto function(){
    return "hello world";
}

Can I apply this behaviour to functions that use enable_if for the SFINAE by return type idiom?

For example, let's consider the following two functons:

#include <type_traits>
#include <iostream>

//This function is chosen when an integral type is passed in
template<class T >
auto function(T t) -> typename std::enable_if<std::is_integral<T>::value>::type {
    std::cout << "integral" << std::endl;
    return;
}

//This function is chosen when a floating point type is passed in
template<class T >
auto function(T t) -> typename std::enable_if<std::is_floating_point<T>::value>::type{
    std::cout << "floating" << std::endl;
    return;
}

int main(){

  function(1);    //prints "integral"
  function(3.14); //prints "floating"

}

As you can see, the correct function is chosen using the SFINAE by return type idiom. However, these are both void functions. The second parameter of enable_if is default set to void. This would be the same:

//This function is chosen when an integral type is passed in
template<class T >
auto function(T t) -> typename std::enable_if<std::is_integral<T>::value, void>::type {
    std::cout << "integral" << std::endl;
    return;
}

//This function is chosen when a floating point type is passed in
template<class T >
auto function(T t) -> typename std::enable_if<std::is_floating_point<T>::value, void>::type{
    std::cout << "floating" << std::endl;
    return;
}

Is there something I can do to these two functions, so that their return type is deduced by the return value?

gcc 4.8.2 (using --std=c++1y)

4 Answers
Related