c++ - Passing vector of derived, templated class -
i'd define general function foo
takes data, perhaps manipulates underlying class variables, , returns int
. however, when attempt create separate function takes vector of foo
objects, compiler fails deduce template parameter. following illustrates i've tried:
#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 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); }
this fails find matching function bar
, notes:
main.cc:16:5: note: template argument deduction/substitution failed: main.cc:24:11: note: mismatched types ‘base<t>’ , ‘derived<double>’
and
main.cc:24:11: note: ‘std::vector<derived<double> >’ not derived \ ‘const std::vector<base<t> >’
forgive me if answer lies in already-posted thread; i've read quite number seem related, don't, knowledge, address issue.
first note std::vector<base<t> >
, std::vector<derived<t> >
different types, if base<std::vector<t>>
base of derived<t>
. type conversion doesn't happen in template type deduction. t
cannot deduced matching second argument y
of type std::vector<derived<double>>
pass bar
std::vector<base<t>>
.
next, suppose make y
of "right" type
std::vector< base<double> > y;
so can pass bar
. in principle can deduce t
matching second parameter in bar
of type std::vector<base<t>>
type std::vector< base<double> >
of y
. t
deduced double
, don't forget x
, pass first parameter bar
, has type vector<double>
, x
deduce t
vector<double>
, of course inconsistent double
deduced y
. type deduction fails.
here simplified example replicates issue.
Comments
Post a Comment