我有可以生成的不同对象。每种对象类型都有不同的成本。我想检查用户是否可以负担得起创建对象之前的特定对象。以下方法不符合此要求:

class Costs {
public:
    int oneCost, anotherCostAttribute; // Actual values for both attribute may differ for the objects
}

class Object {
public:
    virtual Costs getCosts() = 0;
}

class Object_A : public Object {
    // implement getCosts (always the same for all A's)
}

class Object_B : public Object {
    // implement getCosts (always the same for all B's)
}

// Usage:
// I would have to create a specific object just to check the costs:
Object* pObj = new Object_A();
if(avilableResources >= pObj->getCosts()) {
   // Store object, otherwise delete it
}

我的第二个想法是提供虚拟静态函数的某种基类,但是用C++是不可能的:
class Object {
public:
    virtual static Costs getCosts() = 0;
}

仅使用静态Costs属性将无法区分子类成本:
class Object {
public:
    static Costs m_costs; // All objects (A,B,...) would cost the same
}

将成本直接关联到对象的正确方法是什么?

最佳答案

您可以通过模板提供此信息:

template <typename CostsT>
struct Object {
  static CostsT m_costs;
};

例如,您可能有一个Costs基类:
struct Costs {
  virtual int oneCost() = 0;
  virtual int anotherCost() = 0;
};

然后使用Costs的特定子类类型声明对象:
struct Costs_A: Costs {
  virtual int oneCost() override { return 1; }
  virtual int anotherCost() override { return 2; }
};
using Object_A = Object<Costs_A>;

这样,您可以在确定是否实例化Object_A之前检索特定的Costs实例:
Costs costsA = Object_A::m_costs;

09-28 01:49