我想定义一个通用函数foo
,它获取数据,可能操纵底层类变量,并返回一个int
。但是,当我尝试创建一个单独的函数来获取 foo
对象的 vector 时,编译器无法推断出模板参数。以下说明了我的尝试:
#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>
的基础.模板类型推导中不会发生类型转换。所以T
不能通过匹配第二个参数推导出 y
类型 std::vector<Derived<double>>
你传递给bar
与 std::vector<Base<T>>
.
接下来,假设我们制作y
“正确”类型的
std::vector< Base<double> > y;
所以你可以把它传递给bar
.现在原则上我们可以推导出T
通过匹配 bar
中的第二个参数类型 std::vector<Base<T>>
类型为 std::vector< Base<double> >
的 y
.所以T
推导为 double
, 但是不要忘记 x
,您将其作为第一个参数传递给 bar
, 类型为 vector<double>
, 所以来自 x
我们将推断T
作为vector<double>
, 这当然与 double
不一致从 y
推导出来.所以类型推导失败。
Here是一个复制您的问题的简化示例。
关于c++ - 传递派生模板类的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30606577/