【发布时间】:2015-06-02 21:05:41
【问题描述】:
我想定义一个通用函数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> >’
如果答案在已经发布的帖子中,请原谅我;我读过很多似乎相关的文章,但据我所知,并没有解决这个问题。
【问题讨论】: