C++14 http://en.wikipedia.org/wiki/C++14#Function_return_type_deduction将具有可以根据返回值推断其返回类型的函数。
auto function(){
return "hello world";
}
我可以将此行为应用于使用的函数吗启用如果 http://en.cppreference.com/w/cpp/types/enable_if对于 SFINAE 通过返回类型惯用法?
例如,让我们考虑以下两个函数:
#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"
}
正如您所看到的,使用 SFINAE by return type 惯用法选择了正确的函数。
然而,这些都是 void 函数。第二个参数为enable_if
默认设置为void
。这将是相同的:
//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;
}
我可以对这两个函数做些什么,以便通过返回值推断出它们的返回类型吗?
海湾合作委员会 4.8.2 (使用--std=c++1y
)