【发布时间】:2014-01-09 16:27:57
【问题描述】:
C++14 将具有可以根据返回值推断返回类型的函数。
auto function(){
return "hello world";
}
我可以将此行为应用于使用 enable_if 的函数返回类型成语吗?
例如,让我们考虑以下两个函数:
#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 通过返回类型习语选择正确的函数。
但是,这些都是 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;
}
我可以对这两个函数做些什么,让它们的返回类型由返回值推导出来?
gcc 4.8.2(使用--std=c++1y)
【问题讨论】:
标签: c++ template-meta-programming typetraits c++14 enable-if