简体   繁体   中英

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. It seems that C++ does not support partial specialization of a member.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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