Re: Templating composed functions
On Jul 6, 12:29 am, alan <almkg...@gmail.com> wrote:
Hello all, in a project I have I have an abstract base type with some
virtual functions:
Now, I have to use t1() and t2() of an object in several different
ways.
...
This of course means quite a bit of code duplication. There are maybe
3 or so ways, but there are about half a dozen t...() member functions
(and there will probably be more in the future) with the same pattern.
So I thought of using templates:
typedef Base* _ff_type(Base*);
template<_ff_type _ff>
void one_way(Base* b){
std::cout << "one way: " << std::hex
<< (size_t) _ff(b) << std::endl;
}
void another_way(Base* b){
std::cout << "another way: " << std::dec
<< (size_t) _ff(b) << std::endl;
}
The above works but needs to use global functions for the proper call:
inline Base* t1(Base* b){return b->t1();}
inline Base* t2(Base* b){return b->t2();}
...
int main(){
Derived* foo = Derived(NULL, NULL);
Derived* bar = Derived(foo,NULL);
Derived* test = Derived(foo,bar);
one_way<t1>(test);
another_way<t1>(test);
one_way<t2>(test);
another_way<t2>(test);
}
Some questions:
1. Is the above solution Standard C++ compliant? It compiles and
appears to work correctly on g++ 4.2.3
I doubt that the main() routine above compiles. But otherwise, the
function templates look OK to me.
2. Is there a way so that I won't have to declare global t1() and
t2()? Something like this is acceptable:
one_way<Base::t1>(test)
Yes, instead of accepting a function type template parameter,
one_way() and another_way() should accept a (Base class) member
function pointer template parameter. For example:
template <size_t (Base::*MF)()>
size_t one_way( Base& b)
{
return (b.*MF)();
}
Now the compiler will accept your acceptable syntax:
one_way<&Base::t1>(test)
(don't forget the ampersand however).
...as long as I don't have to declare global t1() and t2() (because 1.
they pollute the namespace, and 2.I might need to add several more
member functions, and having to write global versions that effectively
just reflect it gets irritating). I tried Base::t1 like the above but
it says " invalid use of non-static member function". What should
_ff_type be?
See above.
Greg