多种类型的模板专业化 [英] Template specialization for multiple types
问题描述
标题有点含糊.
让我们说我有一个定义为的模板:
Lets say I have a template defined as:
template < typename T >
void foo ( int x ) ;
template <>
void foo<char> ( int x ) ;
template <>
void foo<unsigned char> ( int x ) ;
template <>
void foo<short> ( int x ) ;
...
内部 foo< signed>()
和 foo< unsigned>()
都完全相同.唯一的要求是 T
为8位类型.
Internally both foo<signed>()
and foo<unsigned>()
do exactly the same thing. The only requirement is that T
be an 8bit type.
我可以通过创建另一个模板来基于大小来定义标准类型来做到这一点.
I could do this by creating another template to type define a standard type based on size.
template < typename T, size_t N = sizeof( T ) > struct remap ;
template < typename T, size_t > struct remap< 1 >
{
typedef unsigned char value;
}
...
注意,功能模板不能具有默认参数.此解决方案仅将问题重定位到另一个模板,并且如果有人尝试将结构类型作为参数传递,也会引入问题.
Note, function templates cannot have default parameters. This solution only relocates the problem to another template and also introduces a problem if somebody tried passing a struct type as a parameter.
在不重复这些函数声明的情况下解决此问题的最优雅的方法是什么?
What is the most elegant way to solve this without repeating those function declarations?
这不是C ++ 11问题.
This is not a C++11 question.
推荐答案
您需要您的 remap
特性以简单地从输入类型映射到输出类型,并具有 foo< T>(int)
接口函数委托给 foo_implementation< remap< T> :: type>(int)
实现.即:
You need your remap
trait to simply map from input types to output types, and have your foo<T>(int)
interface function delegate to a foo_implementation<remap<T>::type>(int)
implementation. i.e.:
template <typename T>
struct remap {
// Default: Output type is the same as input type.
typedef T type;
};
template <>
struct remap<char> {
typedef unsigned char type;
};
template <>
struct remap<signed char> {
typedef unsigned char type;
};
template <typename T>
void foo_impl(int x);
template <>
void foo_impl<unsigned char>(int x) {
std::cout << "foo_impl<unsigned char>(" << x << ") called\n";
}
template <typename T>
void foo(int x) {
foo_impl<typename remap<T>::type>(x);
}
也就是说,定义 foo_char
, foo_int
和 foo_short
并实际上从客户端代码中调用正确的代码可能更简单. foo< X>()
在语法上与 foo_X()
并没有太大区别.
That said, it might be realistically simpler to define foo_char
, foo_int
and foo_short
and just call the correct one from client code. foo<X>()
isn't syntactically much different from foo_X()
.
这篇关于多种类型的模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!