C++ 如何减少相同模板专业化的工作量

c++ how to reduce the amout of identical template specializations?

本文关键字:专业化 工作量 何减少 C++      更新时间:2023-10-16

我有这个函子:

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);}
};