Re: Template: given: the method, searched: the class
On 8 Okt., 19:12, t.lehm...@rtsgroup.net wrote:
see following code example (working mechanism):
- - -
struct X{ void test(bool); };
std::for_each(xcont.begin(), xcont.end(), use_method<X>(&X::test,
true));
- - -
Is it possible to write the 'use_method' like this:
- - -
std::for_each(cont.begin(), cont.end(), use_method(&X::test, true));
- - -
How do I get the class from the method?
(If possible - I guess with template specialization - but how?)
This is rather simple: Invent a class template
use_method_type which is returned by a function
template use_method as shown below. Note that
you have to provide an additional specialization
in R (C::*)(Arg) const for const member functions,
but you should be able to transfer that from the
example here:
template <typename T>
struct use_method_type;
template <typename C, typename R, typename Arg>
struct use_method_type<R (C::*)(Arg)> {
use_method_type(R (C::* f)(Arg), Arg value) : f_(f), value_(value)
{}
R operator()(C& obj) const {
return (obj.*f_)(value_);
}
private:
R (C::* f_)(Arg);
Arg value_;
};
template <typename T, typename Arg>
inline use_method_type<T> use_method(T target, Arg value) {
return use_method_type<T>(target, value);
}
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]