Jon*_*Mee 1 c++ templates numeric-limits c++11
有没有办法可以使用std::numeric_limits<T>::is_integer和std::numeric_limits<T>::is_specialized更改模板行为?
例如,我可以这样做:
template < typename T >
void foo( const T& bar )
{
if( std::numeric_limits< T >::is_integer )
{
isInt( bar );
}
else if( std::numeric_limits< T >::is_specialized )
{
isFloat( bar );
}
else
{
isString( bar );
}
}
Run Code Online (Sandbox Code Playgroud)
你拥有的是目前有效的.但是,您应该更喜欢使用SFINAE,<type_traits>因为它会根据类型调度到不同的函数,而不是依赖于分支条件(可能会或可能不会被优化掉).
您可以使用std::enable_if以执行以下操作:
template<typename T,
typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
void foo(const T& t) {
isInt(t);
}
template<typename T,
typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
void foo(const T& t) {
isFloat(t);
}
template<typename T,
typename std::enable_if<!std::is_integral<T>::value &&
!std::is_floating_point<T>::value, int>::type = 0>
void foo(const T& t) {
isString(t);
}
Run Code Online (Sandbox Code Playgroud)
将第二个参数enable_if设置为的原因int是为我们节省一些输入.如果int遗漏了,那么我们必须做typename = typename std::enable_if<std::is_integral<T>::value>::type而不是仅仅将其设置为0可以节省我们几个字符来键入.它们等同于所有意图和目的.
| 归档时间: |
|
| 查看次数: |
679 次 |
| 最近记录: |