Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transferring signature of the method as template parameter to a class

Tags:

c++

templates

I'd like to create a template interface for data-handling classes in my projects.

I can write something like this:

template <class T>
class DataHandler
{
    public:
        void Process(const& T) = 0;
};

Then, suppose, I define a class this way:

class MyClass: public DataHandler<int> 
{
    void Process(const int&) { /* Bla-bla */ }
}

Now, come the question, can I somehow define my template interface in the way that as parameter it will recieve not just type T, but the whole signature of the Process() function.

I would like something working this way:

class MyClass: public DataHandler<void (int&)> 
{
    void Process(const int&) { /* Bla-bla */ }
}

Is it possible? I know that, for instance, boost::signal receives template parameters this way, but, if I understand correctly, they use lot of black-magic there.

like image 551
Lev Avatar asked Mar 01 '10 12:03

Lev


1 Answers

Yep you can. But in C++03, you are bound to do copy/paste code for every number of parameters (not too bad, since here you won't need overloads for const/non-const etc. The constnes is already known!).

template<typename FnType>
struct parm;

template<typename R, typename P1>
struct parm<R(P1)> {
  typedef R ret_type;
  typedef P1 parm1_type;
};

template <class T>
class DataHandler
{
    typedef typename parm<T>::ret_type ret_type;
    typedef typename parm<T>::parm1_type parm1_type;

    public:
        virtual ret_type Process(parm1_type t) = 0;
};

class MyClass: public DataHandler<void (const int&)> 
{
    void Process(const int&) { /* Bla-bla */ }
};

In C++0x, you will be able to write

template <class T>
class DataHandler;

template<typename R, typename ... P>
class DataHandler<R(P...)> 
{
    public:
        virtual R Process(P... t) = 0;
};

class MyClass: public DataHandler<void (const int&)> 
{
    void Process(const int&) { /* Bla-bla */ }
};

How much nicer!

like image 117
Johannes Schaub - litb Avatar answered Nov 07 '22 01:11

Johannes Schaub - litb