传递派生的模板化类的向量

Passing vector of derived, templated class

本文关键字:向量 派生      更新时间:2023-10-16

我想定义一个通用函数foo,它接受数据,可能操作底层类变量,并返回int。然而,当我试图创建一个单独的函数,接受foo对象的向量时,编译器无法推断模板参数。下面是我尝试过的:

#include <vector>
template <typename T>
class Base {
public:
  virtual int foo(const T& x) const = 0;
};
template <typename T>
class Derived : public Base<std::vector<T> > { // specialize for vector data
public:
  virtual int foo(const std::vector<T>& x) const { return 0;}
};
template <typename T>
int bar(const T& x, const std::vector< Base<T> >& y) {
  if(y.size() > 0)
    return y[0].foo(x);
}
int main(int argc, char** argv) {
  std::vector<double> x;
  std::vector< Derived<double> > y;
  bar(x, y);
}

无法找到bar的匹配函数,注释:

main.cc:16:5: note:   template argument deduction/substitution failed:
main.cc:24:11: note:   mismatched types ‘Base<T>’ and ‘Derived<double>’

main.cc:24:11: note:   ‘std::vector<Derived<double> >’ is not derived 
from ‘const std::vector<Base<T> >’

原谅我,如果答案在于一个已经发布的线程;我读过不少似乎与此相关的文章,但据我所知,这些文章都没有涉及到这个问题。

首先注意std::vector<Base<T> >std::vector<Derived<T> >是不同的类型,即使Base<std::vector<T>>Derived<T>的基础。在模板类型推导中不会发生类型转换。因此,不能通过将传递给barstd::vector<Derived<double>>类型的第二个参数ystd::vector<Base<T>>匹配来推导出T

接下来,假设我们将y设置为"right"类型

std::vector< Base<double> > y; 

所以你可以把它传递给bar。现在原则上我们可以通过将std::vector<Base<T>>类型的bar中的第二个参数与ystd::vector< Base<double> >类型进行匹配来推导出T。所以T被推演为double,但是不要忘记你传递给bar的第一个参数x的类型是vector<double>,所以从x我们将T推演为vector<double>,这当然与从y推演的double不一致。所以类型演绎失败。

下面是一个简单的例子,复制了您的问题。