C++ 如何减少相同模板专业化的工作量
c++ how to reduce the amout of identical template specializations?
我有这个函子:
struct functor
{
template<class T> void operator()(T value) // (*)
{
// process the value
}
template<> void operator()<const wchar_t *>(const wchar_t *value) // (**)
{
if (value)
{
// process the value
}
}
template<> void operator()<const char *>(const char *value) // (**)
{
if (value)
{
// process the value
}
}
template<> void operator()<wchar_t *>(wchar_t *value) // (**)
{
if (value)
{
// process the value
}
}
template<> void operator()<char *>(char *value) // (**)
{
if (value)
{
// process the value
}
}
};
如您所见,我有 4 个相同的模板专业化。有没有一种技术可以一次性指定所有这些类型,这意味着以某种方式将所有可能的类型划分为主组 (*( 和专用组 (**(?
谢谢。
编辑
哎呀,修正了一些错别字。
你可以逃脱一个更简单的方案 - 重载!
template<class T>
void foo(T value){ // general
// ...
}
template<class T>
void foo(T* value){ // for pointers!
if(value)
foo(*value); // forward to general implementation
}
另外,我建议将参数作为参考 - const
如果您不需要修改它(或者两者兼而有之,具体取决于您实际需要做什么(:
template<class T>
void foo(T& value){ // general, may modify parameter
// ...
}
template<class T>
void foo(T const& value){ // general, will not modify parameter
// ...
}
如果您想为特定类型集提供特殊实现(即,整个类型集的一个实现(,特征和标签调度可以帮助您:
// dispatch tags
struct non_ABC_tag{};
struct ABC_tag{};
class A; class B; class C;
template<class T>
struct get_tag{
typedef non_ABC_tag type;
};
// specialization on the members of the set
template<> struct get_tag<A>{ typedef ABC_tag type; };
template<> struct get_tag<B>{ typedef ABC_tag type; };
template<> struct get_tag<C>{ typedef ABC_tag type; };
// again, consider references for 'value' - see above
template<class T>
void foo(T value, non_ABC_tag){
// not A, B or C ...
}
template<class T>
void foo(T value, ABC_tag){
// A, B, or C ...
}
template<class T>
void foo(T value){
foo(value, typename get_tag<T>::type()); // dispatch
}
底线是,如果你想对没有任何共同点的类型进行分组,你至少需要一定量的重复(标签、重载等(。
你的意思是这样?
struct functor
{
template<class T> void operator()(T value)
{
// process the value
}
template<class T> void operator()(T* value) // overload, not specialization
{
if (value) {
// process the value
}
}
};
http://ideone.com/P8GLp
如果您只想要这些类型,则其他内容
struct functor
{
protected:
template<class T> void special(T* value) // overload, not specialization
{
if (value) {
// process the value
}
}
public
template<class T> void operator()(T value)
{
// process the value
}
void operator()(char* value) {special(value);}
void operator()(wchar_t* value) {special(value);}
void operator()(const char* value) {special(value);}
void operator()(const wchar_t* value) {special(value);}
};
相关文章:
- 如何使用默认参数等选择模板专业化
- 模板化建造师专业化
- 类模板的成员功能的定义在单独的TU中完全专业化
- 部分专业化和嵌套模板
- 模板专业化可以进入我的.cpp吗?
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 部分专业化和对标准::void_t<>的需求
- "专业化不参与超载"
- 特定好友功能专业化
- 是否可以混合使用SFINAE和模板专业化?
- 多线程减慢程序速度:无错误共享,无互斥锁,无缓存未命中,无小工作量
- 为什么在班级专业化上会出现错误?
- enable_if如何帮助选择类模板的专业化?
- std::initializer_list可以专业化吗?
- 派生类中纯虚拟基方法的专业化
- "expected a '>'"类模板专业化?
- Clang不会编译GCC会编译的模板专业化
- 我可以用clang AST从模板专业化中获得默认的模板参数吗
- 函数模板部分专业化-有什么解决方法吗
- C++ 如何减少相同模板专业化的工作量