1

I have lots of structure like below to make it support thread-safe version and unsafe version:


class NullMutex
{
public:
    void lock() {}
    void unlock() noexcept {}
    bool try_lock() { return true; }
};

class IFoo
{
public:
    virtual void DoSomething() = 0;
};

template<typename Mutex>
class Foo : public IFoo
{
    Mutex m_Mutex;
public:
    void DoSomething() override
    {
        std::lock_guard<Mutex> guard{ m_Mutex };
        // ... some operations
    }
};

using FooSt = Foo<NullMutex>; // Single thread
using FooMt = Foo<std::mutex>; // Multi-thread

int main()
{
    std::shared_ptr<IFoo> foo{ new FooMt };
}

But as you can see, I must write all the implementation in a header file, and it also it increases my compilation time. The worst thing is it makes the classes that need to create it must have a template argument for choose the Mutex type(then this class will also become a template and make the situation worse).

One of the solutions I've thought is to define a using Mutex = std::mutex in a header file. But it needs to include this header file in every file in my project.

Is there a better way to solve this problem? Any suggestion will be really appreciated.

StephanXu
  • 49
  • 5
  • 1
    What's wrong with `using FooSt = Foo; using FooMt = Foo;`? Seems like a good solution to me. (Actuall I was about to make an answer like this, but then I saw you already had it in your code) – Lukas-T May 12 '20 at 16:04
  • 3
    Look up _explicit template instantiation_. You don't _have_ to put everything in a header file when you have a nice constrained list of possible specialisations. – Asteroids With Wings May 12 '20 at 16:07
  • I think this is probably too opinion based. There are a couple of options here that may be of use https://stackoverflow.com/questions/39416978/thread-safe-vector-is-this-implementation-thread-safe/39417596#39417596 and https://stackoverflow.com/questions/820526/c-thread-safe-map/50950667#50950667 – Galik May 12 '20 at 16:10
  • Not that significant, but you could write `template class Foo` which would do away with the double aliasing. – Aluan Haddad May 12 '20 at 16:28
  • The answer to this question depends on the definition of "better." – Travis Gockel May 12 '20 at 18:47

0 Answers0