In C++, what return type to use when the template is variable?

Viewed 67

In the code snippet below, what should I put as the template for MyOtherClass in the return type of the `MyClass::create`` function ?

To make it easier, I can make A , B, C classes all inherit a common class.

And is there a more elegant way of doing this?

template<class MyTemplateClass>
class MyOtherClass{
  //
};

class MyClass{
   public: 
     MyOtherClass<//What do I put here?>
     MyClass::create(const std::string& input){
       if (input == "a"){
         return MyOtherClass<A>(); //A is a class
       }
       if (input == "b"){
         return MyOtherClass<B>(); // B is a class
       }
       return MyOtherClass<C>(); // C is a class
     }
};
1 Answers

Short answer is, you can't as is.

You can do something like this either through inheritance (A, B and C inherits from a common base class), or with std::variant, or with type erasure (MyOtherClass inherits from something)

The question is more about how do you plan on using what comes out of the function?

Related