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"));
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
.
You can use the boost.type_traits library to remove the const-ness of the parameter using boost::remove_const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With