如何正确使用标签分派来选择构造函数 [英] How to properly use tag dispatching to pick a constructor

查看:77
本文介绍了如何正确使用标签分派来选择构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为嵌入式系统实现一组互斥锁和锁定类。我以前从未使用过标签分发功能,而且不确定是否做对了。提升文档中包含的描述只是这样:

I'm trying to implement a set of mutex and lock classes for an embedded system. I've never used tag dispatching before, and I'm not sure if I'm doing it right. The description included in the boost documentation simply has this:

struct input_iterator_tag { };

并使用它来选择专门的模板函数。我没有模板,我只想根据标签的存在选择特定的构造函数:

and uses it to pick a specialized template function. I don't have a template, I just want to pick a specific constructor based on the presence of a tag:

// in mutex.h:

struct TryLock { };
// defined nowhere, i.e. there's no cpp file for this:
extern TryLock try_lock; 

template<typename MutexType>
class ScopedLock
{
  public:
    ScopedLock(MutexType& mtx) : m_mtx(mtx), m_acquired(true)
    {
      m_mtx.lock();
    }
    ScopedLock(MutexType& mtx, TryLock) : m_mtx(mtx)
    {
      m_acquired = m_mtx.tryLock();
    }
  ...
}

代码我有一个要锁定的互斥锁:

and somewhere in my code I have a mutex which I want to lock:

Mutex mtx;
ScopedLock<Mutex> lock(mtx, try_lock);

这可以正常工作。我只是好奇是否可以摆脱外部TryLock try_lock; ,因为我觉得它有点多余。

This compiles fine and works. I'm just curious if I can get rid of the extern TryLock try_lock;, as I have the impression that it's somewhat superfluous.

推荐答案

如果将try_lock的用法替换为临时构造函数,则不需要try_lock的外部声明:

You won't need the extern declaration for try_lock, if you replace its usage in the lock constructor call with a temporary:

Mutex mtx;
ScopedLock<Mutex> lock(mtx, TryLock());

否则,编译器会将try_lock的副本传递给构造函数,此时它将要链接

Otherwise the compiler will pass a copy of try_lock to your constructor, at which point it will want to link against it.

当标准库需要执行此操作时,它使用 constexpr

When the standard library needs to do this, it uses constexpr:

struct piecewise_construct_t { };
constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t();

这篇关于如何正确使用标签分派来选择构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆