简体   繁体   中英

Return type agnostic template class member function

I have a class like:

tempate<class TReturn>
struct MyClass {
 template<class T>
 TReturn doSomething(const T &t) {
  // Do something
  return someValue;
 }
};

Now TReturn can be anything even void but in case it is void I want no return statement at the end and some minor different code in the function. What I want is a different function body depending on the return type. I'm using C++11 so if constexpr is not possible for me. Is there any way to to this in plain C++11?

You can provide a specialization of your class for void :

tempate<>
struct MyClass<void> {
 template<class T>
 void doSomething(const T &t) {
  // Do something else
 }
};

If the class is in fact larger than you show and you want to specialize just this one function and not the whole thing, then a) it was probably unwise to make TReturn a parameter of the class when only a small part of the class depends on it, but b) there are ways to simulate that. Eg you could sort of "partially specialize" the method by indirecting through a helper class (unlike function templates, class templates allow partial specialization). Something like this:

tempate<class TReturn> struct MyClass;

namespace internal {
  template <typename TReturn, typename T>
  class MyClassDoSomethingHelper {
    static TReturn Run(MyClass<TReturn>* that, const T &t) {
      // do something
      return someValue;
    }
  };

  template <typename T>
  class MyClassDoSomethingHelper<void, T> {
    static void Run(MyClass<void>* that, const T &t) {
      // do something else
    }
  };
}  // namespace internal

tempate<class TReturn>
struct MyClass {
 template<class T>
 TReturn doSomething(const T &t) {
   return internal::MyClassDoSomethingHelper<TReturn, T>::Run(this, t);
 }
};

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