如何隐藏模板库的参数类型 class

How to hide param type of template base class

不确定这是否可能,但这里...

我试图通过执行以下操作来隐藏模板库 class 的参数:

到目前为止一切顺利,但问题是我工厂的 return 类型 class 是 IBase,因此调用 foo 的默认实现而不是 DerivedA 或 DerivedB:(

无论如何,这种方法是否有效?还是回到绘图板?

// Common interface
class IBase {
public:
  virtual std::string foo() { return "IBase"; };
}

// Template base class
template <typename T>
class Base : public IBase {
public:
  Base(T value) : m_precious(value) {}
  virtual ~Base() {}
protected:
  T m_precious;
}

// Concrete derived classes
class DerivedA : public Base<int> {
public:
  DerivedA(int value) : Base<int>(value) {}

  virtual std::string foo() override {
   return "DerivedA";
  };
}

class DerivedB : public Base<float> {
public:
  DerivedB(float value) : Base<float>(value) {}

  virtual std::string foo() override {
   return "DerivedB";
  };
}

// Factory interface
class Factory {
public:
  template<typename T>
  static IBase create(T value);
};

template<>
IBase Factory::create<int>(int value) {
  return DerivedA(value);
}

template<>
IBase Factory::create<float>(float value) {
  return DerivedB(value);
}

// Caller
int main() {
  int   valueA = 3;
  float valueB = 3.14;

  // This is how I want to use the API
  IBase A = Factory::create(valueA);
  IBase B = Factory::create(valueB);

  std::cout << A.foo() << std::endl;
  std::cout << B.foo() << std::endl;
}

以上代码打印:

IBase
IBase

但我想要这个:

DerivedA
DerivedB

您目前有对象切片,您的代码应该是这样的:

// Factory interface
class Factory {
public:
  template<typename T>
  static std::unique_ptr<IBase> create(T value);
};

template<>
std::unique_ptr<IBase> Factory::create<int>(int value) {
  return std::make_unique<DerivedA>(value);
}

template<>
std::unique_ptr<IBase> Factory::create<float>(float value) {
  return std::make_unique<DerivedB>(value);
}

使用情况:

auto A = Factory::create(valueA);
auto B = Factory::create(valueB);

std::cout << A->foo() << std::endl;
std::cout << B->foo() << std::endl;