简体   繁体   English

部分特化类模板的单个成员的解决方法?

[英]Workaround to partially specialize a single member of a class template?

I have a class which has two template parameters, the doLeft/doRight member function only relies on one template parameter (ie Left/Right), and doBoth relies on both parameters.我有一个类有两个模板参数,doLeft/doRight 成员函数只依赖一个模板参数(即Left/Right),而doBoth 依赖两个参数。 It seems that C++ does not support partial specialization of a member.似乎 C++ 不支持成员的部分专业化。

What is the best way to approximate it?近似它的最佳方法是什么?

template<typename Left, typename Right>
class RightandLeft {
   void do() {
      doLeft();
      doRight();
      doBoth();
   }
   void doLeft();
   void doRight();
   void doBoth();
}

// when left type is int64, do something based on int64, 
// right type can be any type. How should I achieve it?
template<typename right>
void RightandLeft<int64_t, right>::doLeft() {
   
}

// when right type is string, do something based on string, 
// left type can be any type. How should I achieve it?
template<typename left>
void RightandLeft<left, string>::doRight() {
   
}

template<typename left, typename right> 
void RightandLeft<left, right>::doBoth(){};

Restructure, then delegate.重组,然后委托。

template<typename A>
struct Left {
  void doImpl() {}
};

template<>
inline void Left<int64_t>::doImpl() {
  // Do something else
}

template<typename B>
struct Right {
  void doImpl() {}
};

template<>
inline void Right<string>::doImpl() {
  // Do something else
}

template<typename L, typename R>
class RightandLeft : Left<L>, Right<R> {
   void doImpl() {
      Left<L>::doImpl();
      Right<R>::doImpl();
      doBoth();
   }
   void doBoth();
};

You can't partially specialize just one single member , since that implies you partially specialized the class (which you did not).您不能部分专门化一个成员,因为这意味着您部分专门化了该类(您没有)。 But you can fully specialize a member and the compiler may assume its part of the primary template.但是你可以完全特化一个成员,编译器可能会假设它是主模板的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM