I have a class that wraps any type and only allows operations on that type via a specific function. This helps in many cases where I need control of the flow, synchronization and more.
So I have a simple template class called ObjectWrapper
that exposes 1 UseMe
method, to allow working with the inner object.
For example if I need to print every time this object is used I can have the following code:
template <typename Object>
class ObjectWrapper
{
public:
template <typename Functor>
typename std::result_of<Functor(Object&)>::type UseMe(const Functor& functor)
{
std::cout << "Someone is using me!" << std::endl;
return functor(m_object);
}
private:
Object m_object;
};
And I can use it like this:
void main()
{
mySpecialString.UseMe([](std::string& innerObject) {
innerObject = "My Special string";
});
mySpecialString.UseMe([](std::string& innerObject) {
std::cout << innerObject << std::endl;
});
size_t length = mySpecialString.UseMe([](std::string& innerObject) {
return innerObject.size();
});
std::cout << length << std::endl;
}
which will print:
Someone is using me!
Someone is using me!
My Special string
Someone is using me!
17
This is exactly what I want but it has 1 flaw which is that developers can write the following:
void main()
{
ObjectWrapper<std::string> mySpecialString;
mySpecialString.UseMe([](std::string innerObject) {
innerObject = "My Special string";
});
mySpecialString.UseMe([](std::string innerObject) {
std::cout << innerObject << std::endl;
});
size_t length = mySpecialString.UseMe([](std::string innerObject) {
return innerObject.size();
});
std::cout << length << std::endl;
}
which will print:
Someone is using me!
Someone is using me!Someone is using me!
0
[For those who missed it the string is passed by value to the lambda instead of by ref as I intended]
I thought that the typename std::result_of<Functor(Object&)>::typ
will help enforce passing the parameter by ref, but it doesn't.
I also though of using static_assert
but can't figure out how to get the type of the passed parameter.
How can I force the users of this ObjectWrapper
to get the templated Object
by reference only?