std :: numeric_limits作为条件 [英] std::numeric_limits as a Condition
问题描述
有没有办法使用 std :: numeric_limits< T> :: is_integer
和 std :: numeric_limits< T> :: is_specialized
更改模板行为?
Is there a way that I can use std::numeric_limits<T>::is_integer
and std::numeric_limits<T>::is_specialized
to change template behavior?
例如,我可以这样做:
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 );
}
}
推荐答案
明显的答案是你可以使用 std :: enable_if
。
The "obvious" answer is that you could use something like std::enable_if
.
例如:
template<typename T>
typename std::enable_if<std::numeric_limits<T>::is_integer, void>::type
foo(const T &bar) { isInt(bar); }
template<typename T>
typename std::enable_if<std::numeric_limits<T>::is_specialized, void>::type
foo(const T &bar) { isFloat(bar); }
这种方法的问题是,这是不明确的$ c> int 参数,因为 numeric_limits< int> :: is_specialized == true
。
The problem with this approach is that this is ambiguous for (as an example) an int
parameter, since numeric_limits<int>::is_specialized == true
.
要解决这个问题, numeric_limits
,个人。您还可以使用布尔条件来测试所需的确切条件:
To resolve this, I would simply use a better trait than numeric_limits
, personally. You can also use boolean conditions to test for the exact condition you want:
template<typename T>
typename std::enable_if<std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_integer, void>::type
foo(const T &bar) { isFloat(bar); }
这篇关于std :: numeric_limits作为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!