繁体   English   中英

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

[英]Passing vector of derived, templated class

我想定义一个通用函数foo ,它接收数据,也许操纵基础类变量,并返回一个int 但是,当我尝试创建一个采用foo对象向量的单独函数时,编译器无法推断出template参数。 以下说明了我尝试过的内容:

#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> >’

如果答案在已经发布的帖子中,请原谅我。 我读了很多看似相关的文章,但据我所知,并没有解决这个问题。

首先请注意,即使Base<std::vector<T>>Derived<T>的基数, std::vector<Base<T> >std::vector<Derived<T> >是不同的类型。 模板类型推导中不会发生类型转换。 所以T无法通过匹配的第二个参数来推断y类型的std::vector<Derived<double>>您传递给barstd::vector<Base<T>>

接下来,假设我们将y “正确”类型

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

因此您可以将其传递给bar 现在,原则上我们可以通过将std::vector<Base<T>>类型的bar中的第二个参数与y std::vector< Base<double> > std::vector<Base<T>>类型匹配来推导T 因此, T被推导为double ,但是请不要忘记将x作为第一个参数传递给bar ,其类型为vector<double> ,因此从x推论出Tvector<double> ,这当然是不一致的由y推论出double 因此类型推导失败。

是一个简化的示例,可以复制您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM