c++ - using template assignment operator -
having next code, why first assignment doesn't phone call template operator=
in foo
, sec does? going 1 here? there compiler-generated 1 first assignment if user defined template exists?
#include <iostream> using namespace std; struct uberfoo { }; struct foo : public uberfoo { template<typename t> void operator=(const t& v) { cout << "const t&" << endl; set(v); } template<typename t> void operator=(t& v) { cout << "t&" << endl; homecoming set(v); } virtual void set(const foo&) { cout << "foo::set(const foo&)" << endl; } virtual void set(const uberfoo&) { cout << "foo::set(const uberfoo&)" << endl; } }; struct bar : public foo { virtual void set(const foo&) { cout << "bar::set(const foo&)" << endl; } virtual void set(const uberfoo&) { cout << "bar::set(const uberfoo&)" << endl; } }; int main() { bar a, b; foo & pa = a; const foo& rb = b; const uberfoo & urb = b; cout << "first" << endl; pa = rb; cout << endl << "second" << endl; pa = urb; homecoming 0; }
the compiler still generating non-templated operator=
first assignment binds to. in sec assignment, templated operator=
improve candidate (because involves no cast), 1 picked.
you can see adding next in code:
foo& operator=(const foo&) = delete;
or forcing proper template call:
pa.operator=<foo>(b);
the standard says (emphasis mine):
12.8 copying , moving class objects, §12.8/17, page 271:
a user-declared re-create assignment operator x::operator= non-static non-template fellow member function of class x 1 parameter of type x, x&, const x&, volatile x& or const volatile x&
§12.8/18, same page:
if class definition not explicitly declare re-create assignment operator, 1 declared implicitly.
c++ templates
No comments:
Post a Comment