C ++多态模板类,模板类型对象的实例化

问题描述 投票:-1回答:1

我有以下情况,我想实例化模板类型的对象。我希望模板类型对象的实例化取决于“实例化器”类。

template <class T>
class Base
{
public:
  Base(){}

  void do_something()
  {
    T obj = this->Test();
    // do something with object
  }

  virtual T Test()
  {
   return T(5);
  }
};


template <class T>
class Derived : public Base<T>
{
public:
  Derived() : Base<T>() {}
  virtual T Test()
  {
    return T(5, 6);
  }
};

class Test1
{
public:
  Test1(int x){}
};
class Test2 : public Test1
{
public:
  Test2(int x, int y) : Test1(x) {}
};

稍后在我的代码中,我想使用基础或派生对象。它们对功能obj中的模板类型对象(do_something())执行操作。我想让obj的实例化取决于实现Test()功能的功能。Base仅应与具有相同构造函数的Test1类型的对象或Test1的派生类一起使用。Derived应该只对与Test2具有相同构造函数的对象起作用。

Base<Test1>(); // works
Base<Test2>(); // doesn't work, but should not work by my design and throw a compile error
Derived<Test1>(); // same
Derived<Test2>();  // should work, but doesn't,
// since Base::Test() still exists, but cannot be compiled due to wrong constructor of T

是否有实现上述行为的方法?还是我可以进行设计更改?

c++ templates polymorphism instantiation
1个回答
0
投票

您可能将Base更改为对于任何T都是正确的:

template <class T>
class Base
{
public:
    Base(){}

    void do_something()
    {
        T obj = this->Test();
        // do something with object
    }

    virtual T Test()
    {
        if constexpr (std::is_constructible_v<T, int>) {
            return T(5);
        }
        throw std::runtime_error("should not be called");
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.