I have a class template which looked like this:
template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
T f() const {
resource_lock a_lock(some_mutex);
return some_policy.some_operation(some_data);
}
private:
T some_data;
mutable Mutex some_mutex;
SomePolicy some_policy;
};
If not used concurrently, we have a dummy mutex type which has all the member functions as inlined empty functions and no data. There are policies that have per-instance data and those that do not have any data.
This is library code and it turns out that this class template gets used in application code where the extra bytes matter which are needed for the data members some_mutex
and some_policy
even when they are empty classes. So I want to make use of the empty base optimization. For the policy, this is easy:
template<typename T, typename Mutex, typename SomePolicy>
class my_class {
public:
T f() const {
resource_lock a_lock(the_data.some_mutex);
return the_data.some_operation(the_data.some_data);
}
private:
struct data : SomePolicy {
T some_data;
mutable Mutex some_mutex;
};
data the_data;
};
However, given that some_mutex
is mutable
, I don't know how to make it a base class without making the_data
, and thus all data, mutable
, thereby completely taking over the compiler's responsibility to protect me from silly constness mistakes.
Is there a way to make a turn a mutable
data member into a base of a non-mutable data member's class?