考虑函数 template<typename T> void Fun(T t);
.
我怎样才能分别对整型和浮点型有不同的实现?
我猜积木是 std::enable_if
, std::is_integral
, std::is_floating_point
.但我不能以一种优雅的方式将它们放在一起 :-( .
附言我有可用的 C++11。
最佳答案
参见 std::enable_if 的示例代码在 cppreference.com .
编辑:
将上面链接中的代码改编如下:
#include <type_traits>
#include <iostream>
template<class T>
typename std::enable_if<std::is_integral<T>::value>::type foo(T t)
{
std::cout << "is integral" << std::endl;
}
template<class T>
typename std::enable_if<std::is_floating_point<T>::value>::type foo(T t)
{
std::cout << "is real" << std::endl;
}
int main()
{
foo(1);
foo(1.0);
}
enable_if
的定义是template< bool B, class T = void > struct enable_if;
.这为返回值类型提供了以下选项:
template<class T>
typename std::enable_if<std::is_integral<T>::value>::type foo(T t) // void return type
template<class T>
typename std::enable_if<std::is_integral<T>::value, T>::type foo(T t) // return type from template parameter
template<class T>
typename std::enable_if<std::is_integral<T>::value, size_t>::type foo(T t) // fixed return type
关于c++ - 如何分别针对整型和浮点型专门化模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21973389/