C ++ Template Programming - Deferred Function Calls

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

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

The problem I encountered is this:

 Task1<const Foo&> MyTask; 

This will cause the parameter to be held as a reference to a constant. Does anyone know a good solution to get around this? I could apply rules like delegate signature always accepting const & params, but that seems restrictive. I can always have two task structures (one for ref and one for value), but that seems unpleasant.

Another solution would be to create the following:

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

In any case, will T2 default to the same type as T1? Thus, whenever I have a signature for a method value, I do not need to have additional template parameters.

EDIT: The template is used for multi-threaded task scheduler. Here is an example:

 void MyClass::Populate(const std::string& instrText); CTaskScheduler::Schedule(Task1<const std::string&>(this, &MyClass::Popluate, "MyString")); 
+4
source share
4 answers

You can take a look at the implementation of function<> either boost or the upcoming standard. Essentially, you can just use function<> . I think the solution was (before C ++ 0x) to always keep a copy of the arguments, if the user needs reference semantics, they can use a reference shell.

Regarding how to get the value, you can take a look at some simple metapounds 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 .

+8
source

You can use the boost.type_traits library to remove the parameter constant with boost::remove_const .

+2
source

In addition to boost :: type_traits, there is a boos :: call_traits library specifically designed to solve such problems. It also provides mechanisms to avoid links to link problems.

+2
source

boost :: remove_const should help you in this case:

 template <typename T> struct Task1 { typename boost::remove_const<T>::type Arg1; Delegate<T> TaskDelegate; }; 

Alternatively, you can avoid using boost if you use specialized specialization for const types:

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

(Warning: not verified)

+1
source

All Articles