C ++ 11-enable_if-类定义之外的函数实现 [英] C++11 - enable_if - function implementation outside of class definition
问题描述
如何使用具有enable_if的模板实现功能?
How can I implement function with template that have enable_if?
class Test
{
public:
Test(){}
~Test(){}
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type>
void do_something(T v);
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type>
void do_something(T v);
};
如何为类定义之外的其他类型(即,内联文件)实现 do_something
?
How to implement do_something
for different types outside the class definition (i.e. in inline file)?
推荐答案
您在返回类型上使用 enable_if
. cppreference :
You use enable_if
on the return type. This is described on cppreference:
一个常见的错误是声明两个仅在默认模板参数方面不同的函数模板.这是非法的,因为默认模板参数不是功能模板签名的一部分,并且声明具有相同签名的两个不同功能模板是非法的.
A common mistake is to declare two function templates that differ only in their default template arguments. This is illegal because default template arguments are not part of function template's signature, and declaring two different function templates with the same signature is illegal.
#include <iostream>
#include <type_traits>
class Test
{
public:
Test(){}
~Test(){}
template<typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
do_something(T v);
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, void>::type
do_something(T v);
};
template<typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
Test::do_something(T v) { std::cout << "Integral\n"; }
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, void>::type
Test::do_something(T v) { std::cout << "Floating point\n"; }
int main()
{
Test t;
t.do_something(1);
t.do_something(3.14);
}
这篇关于C ++ 11-enable_if-类定义之外的函数实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!