【问题标题】:How to make a family of functions which will take as an argument vectors of different classes?如何制作一系列函数,将其作为不同类的参数向量?
【发布时间】:2016-11-27 12:57:05
【问题描述】:

就像问题一样。我想做一个能够管理不同向量的函数。我考虑过使用继承。

class A : public C {public: void do();};
class B : public C {public: void do();};
class C {
public:
virtual void do();
}

现在我的函数应该在多个类上运行,这里是:A 和 B

void function(vector<C*>* array) {
   for (int i = 0; i < array->size(); i++) {
      array->at(i)->do();
   }
}

在我的程序中,我是这样使用这个函数的:

vector<A*>* array = new vector<A*>();
array->push_back(new A());
function(array);

但它不起作用。我不知道如何解决这个问题。

The Visual Studio reports that it cannot convert from vector<A*>* to vector<C*>*

【问题讨论】:

  • 那么为什么不用模板函数呢?
  • 我读过一些关于模板的东西,但我不知道该怎么做。我会尝试使用它们。
  • @FirstStep:他没有说不是模板函数。他说他不知道如何解决这个问题。解决方案很可能是一个模板函数。
  • newvector 很少有充分的理由。您可能只需声明一个vector,然后通过引用传递它。

标签: c++ generics inheritance vector


【解决方案1】:

使用模板,例如:

template<typename T>
void function(vector<T*>* array) {
   for (int i = 0; i < array->size(); i++) {
      array->at(i)->do();
   }
}

请注意,您不需要 C。您可能希望限制为特定类型。这通常通过std::enable_if&lt;&gt; 完成,例如:

template<typename T>
typename std::enable_if< std::is_same<T, A>::value
                      || std::is_same<T, B>::value, void >::type function(vector<T*>* array) { /...

如果您想检查完全匹配,请使用std::is_same&lt;&gt;,如果您对继承类型没问题,请使用std::is_base_of&lt;&gt;

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 2013-06-03
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2019-03-19
    • 1970-01-01
    • 2013-02-22
    相关资源
    最近更新 更多