【发布时间】:2013-02-27 14:52:33
【问题描述】:
我有几个我想根据类型质量专门化的函数,例如“字符、有符号整数、无符号整数、浮点数、指针”;使用 type_traits 似乎是 the 方法,并且具有类似于以下的代码:
#include <tr1/type_traits>
#include <iostream>
template<bool, typename _Tp = void>
struct enable_if
{ };
template<typename _Tp>
struct enable_if<true, _Tp>
{
typedef _Tp type;
};
template< typename T >
inline void
foo_impl( typename enable_if< std::tr1::is_integral< T >::value, T >::type const& )
{
std::cout << "This is the function-overloaded integral implementation.\n";
}
template< typename T >
inline void
foo_impl( typename enable_if< std::tr1::is_floating_point< T >::value, T >::type const& )
{
std::cout << "This is the function-overloaded floating-point implementation.\n";
}
template< typename T >
inline void
function_overloads_foo( T const& arg )
{
foo_impl< T >( arg ); // vital to specify the template-type
}
void function_overloads_example()
{
function_overloads_foo( int() );
function_overloads_foo( float() );
}
除了在我的真实代码中,我还有bar、baz等,还有foo。
但是,我想将所有这些功能按质量分组到一个模板类中,作为static 方法。这怎么做最好?这是我使用标签、SFINAE 和部分专业化的天真和失败的尝试:
struct IntegralTypeTag;
struct FloatingPointTypeTag;
template< typename T, typename U = void >
class Foo
{
};
template< typename T >
class Foo< T, typename enable_if< std::tr1::is_integral< T >::value, IntegralTypeTag >::type >
{
static void foo( T const& )
{
std::cout << "This is the integral partial-specialization class implementation.\n";
}
};
template< typename T >
class Foo< T, typename enable_if< std::tr1::is_floating_point< T >::value, FloatingPointTypeTag >::type >
{
static void foo( T const& )
{
std::cout << "This is the floating-point partial-specialization class implementation.\n";
}
};
template< typename T >
inline void
partial_specialization_class_foo( T const& arg )
{
Foo< T >::foo( arg );
}
void partial_specialization_class_example()
{
partial_specialization_class_foo( int() );
partial_specialization_class_foo( float() );
}
注意:在我的真实代码中,我会使用 bar、baz 等,以及 foo 静态方法。
仅供参考,这是 C++03。
顺便说一句,我是否以传统方式进行模板化函数重载?
【问题讨论】:
-
我不明白为什么
function_overload_foo()是“指定模板类型的关键”。你在那里什么都没做,只是转发 -
是的,我也是这么认为的,但是我的编译器 'gcc-4.7' 没有它就会抱怨:错误:没有匹配函数调用 'foo_impl(const int&)' 注意:候选人是:注意:模板
void foo_impl(const typename enable_if<:tr1::is_integral>::value, T>::type&) 注意:模板参数推导/替换失败:注意:无法推导模板参数'T ' 注意:模板 void foo_impl(const typename enable_if<:tr1::is_floating_point>::value, T>::type&) 注意:模板参数推导/替换失败:注意:无法推导模板参数'T' -
@AndyProwl:如果您不提及模板参数,编译器无法从函数参数中推断出它,因为它是不可推断的上下文。 See this to know why it is non-deducible
-
@Nawaz:当然。我只是把整本书读得太肤浅了。谢谢。
标签: c++ templates static-methods sfinae partial-specialization