Re: Specialization of member functions without inheritance
"Allan Douglas" <allandouglas@gmail.com> wrote in
news:1171497259.272126.205790@j27g2000cwj.googlegroups.com:
[snip]
But I don't like this solution because I just need to specialize the
function, not the entire class. And I don't want to use inheritance.
I clearly didn't read well the first time (including the subject of
the message-ha). Why don't you want to use private inheritance? It's
morally equivalent to composition with the syntactic sugar of having
"using" to enable you to call directly to the derived class function.
But if you insist on avoiding inheritance, use Doer2.
The previous example slightly modified:
#include <iostream>
// Boost.Function rather than raw function pointers
#include <boost/function.hpp>
using namespace std;
#define PARTIALLY_SPECIALIZED
#define COMPOSITION_DOER
template <typename T, typename U>
struct FnDelegate
{
explicit FnDelegate(boost::function<T(U)> i_fn):m_fn(i_fn) {}
T doit(U u)
{
return m_fn(u);
}
private:
boost::function<T(U)> m_fn;
};
#ifdef PARTIALLY_SPECIALIZED
template <typename U>
struct FnDelegate<void, U>
{
explicit FnDelegate(boost::function<void(U)>){}
void doit(U u)
{
cout << "partially specialized" << endl;
}
};
#endif
template <typename T, typename U>
struct Doer1: private FnDelegate<T, U>
{
explicit Doer1(boost::function<T(U)> i_fn):FnDelegate<T,U>(i_fn){}
using FnDelegate<T,U>::doit;
};
template <typename T, typename U>
struct Doer2
{
explicit Doer2(boost::function<T(U)> i_fn):delegate(i_fn){}
T doit(U u)
{
return delegate.doit(u);
}
private:
FnDelegate<T, U> delegate;
};
void retVoid(int x)
{
cout << "retVoid got " << x << endl;
}
int retInt(int x)
{
cout << "retInt got " << x << endl;
return x;
}
#ifdef COMPOSITION_DOER
// note: I would never seriously consider doing this
#define Doer Doer2
#else
#define Doer Doer1
#endif
int main(int argc, char const * argv[])
{
Doer<void, int> doer1(retVoid);
Doer<int, int> doer2(retInt);
doer1.doit(1);
int y = doer2.doit(2);
return 0;
}
[snip]
There is a way to specialize only the member function? The FAQ doesn't
talk so much about class and function members specialization.
As the previous poster said, you can't partially specialize part of a
class's definition. You can partially specialize something filling a
delegate role, such as a "part-of" implemented via composition or
private inheritance.
SFINAE to enable different construction behavior still seems like a
reasonable exercise.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]