Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template programming - Deferred function calls

I am looking for an elegant solution to the following problem. I have a task struct that I use for deferred function calls.

template <typename T> struct Task1
{
    T Arg1;
    Delegate<T> TaskDelegate;
};

The problem I'm having is this:

Task1<const Foo&> MyTask;

This will result in the parameter being held as a const reference. Does anyone know a nice solution to get round this? I could enforce rules such as the delegate signature always taking const& params but this seems restrictive. I could always have two task structs (one for ref and one for value) but this seems nasty.

The other solution would be to create the following:

template <typename T1, typename T2> struct Task1
{
    T2 Arg1;
    Delegate<T1> TaskDelegate;
};

Is there anyway to default T2 to be the same type as T1? That way whenever I have a method value signature I don't need to have the additional template params.

EDIT: The template is used for a multithreaded task scheduler. Here is an example:

void MyClass::Populate(const std::string& instrText);

CTaskScheduler::Schedule(Task1<const std::string&>(this, &MyClass::Popluate, "MyString"));
like image 752
Downie Avatar asked Aug 19 '11 16:08

Downie


2 Answers

You could take a look at the implementation of function<> either in boost or the upcoming standard. As a matter of fact, you can just use function<>. I think that the solution there was (before C++0x) to always store a copy of the arguments, if the user wants reference semantics they can use a reference wrapper.

As to how to get to a value, you can take a look at some simple metafunction to remove const or &:

// Remove reference:
template <typename T>
struct remove_reference {
   typedef T type;
};
template <typename T>
struct remove_reference<T&> {
   typedef T type;
};

Similarly for const.

like image 169
David Rodríguez - dribeas Avatar answered Sep 19 '22 06:09

David Rodríguez - dribeas


You can use the boost.type_traits library to remove the const-ness of the parameter using boost::remove_const.

like image 24
Diego Sevilla Avatar answered Sep 17 '22 06:09

Diego Sevilla