Re: virtual function template workaround
On 4/2/07 6:07 AM, in article
1175499698.376398.282600@n76g2000hsh.googlegroups.com, "John Moeller"
<fishcorn@gmail.com> wrote:
...
// Note that including the type in the read_ function name
// is done primarily for the purposes of exposition.
// It would probably be considered better form to overload
// a single name (say, "read_value") instead.
I think that you must actually name them differently, because if you
want to do this:
No, overloading the various "read_type()" methods with a single
"read_value()" method (as shown below) works just as well.
class data_access
{
public:
...
virtual void read_value(const string& query, int& outInt ) = 0;
virtual void read_value(const string& query, string& outString)= 0;
virtual void read_value(const string& query, timeval& outDate) = 0;
...
};
...
Specializations establish the actual pairings:
// for an int value_type call data_access::read_int()
template <>
const data_traits< int >::MF
data_traits< int >::read_method = &data_access::read_int;
template <>
const data_traits< string >::MF
data_traits< sint >::read_method = &data_access::read_string;
You couldn't do it if they were each named read_value. You can't get
a pointer-to-member to an overloaded member function, can you?
Yes, you can - in fact in this case, just replace each of the various
&data_access::read_int, &data_access::read_string and the other
individualized member pointers with a common "&data_access::read_value"
member pointer expression:
template <>
const data_traits< int >::MF
data_traits< int >::read_method = &data_access::read_value;
template <>
const data_traits< string >::MF
data_traits< string >::read_method = &data_access::read_value;
Since the definition of the data_traits "MF" typedef varies according to the
template's parameterized type, the compiler is able to pick the correct
read_value overload on the right because its type must match the MF typedef
type that appears on the left-hand side of the expression.
Note that even in contexts in which no member pointer typedef has been
defined, a program may always use an explicit cast to disambiguate a member
pointer to an overloaded method.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]