传递派生的模板化类的向量
Passing vector of derived, templated class
我想定义一个通用函数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>
的基础。在模板类型推导中不会发生类型转换。因此,不能通过将传递给bar
的std::vector<Derived<double>>
类型的第二个参数y
与std::vector<Base<T>>
匹配来推导出T
。
接下来,假设我们将y
设置为"right"类型
std::vector< Base<double> > y;
所以你可以把它传递给bar
。现在原则上我们可以通过将std::vector<Base<T>>
类型的bar
中的第二个参数与y
的std::vector< Base<double> >
类型进行匹配来推导出T
。所以T
被推演为double
,但是不要忘记你传递给bar
的第一个参数x
的类型是vector<double>
,所以从x
我们将T
推演为vector<double>
,这当然与从y
推演的double
不一致。所以类型演绎失败。
下面是一个简单的例子,复制了您的问题。
相关文章:
- 如何通过派生类函数更改基类中的向量
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 如何创建派生对象的向量?
- 将shared_ptr的向量复制到抽象基的派生类
- 基类到派生类的强制转换向量
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- 有没有办法复制派生类指针的向量而不将其强制转换为基类?
- 无法将派生类存储在基类指针的向量中
- 在 c++ 中,如何使用向量调用派生类?
- 基类类型向量中的派生结构
- 按类型排序向量并按类型或派生类型搜索
- 替换派生对象向量中的对象"no matching function to call"
- 用于填充 Base 和派生对象的 shared_ptr 向量的函数模板
- 使用 shared_ptr 的派生类对象的向量
- 指向派生类的向量的指针
- 如何在另一个类的向量中调用派生类的析构函数
- 将抽象派生类对象存储在基类向量中
- 使用 boost::序列化将派生类指针序列化为向量时出现问题
- 如何从基类向量达到派生的类变量
- 向量派生类的复制构造函数