gpt4 book ai didi

c++ - 如何正确使用标签调度来选择构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:27 24 4
gpt4 key购买 nike

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

struct input_iterator_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();
}
...
}

在我的代码中某处我有一个我想锁定的互斥体:

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

这可以很好地编译并工作。我只是好奇我是否可以摆脱 extern TryLock try_lock;,因为我觉得它有点多余。

最佳答案

如果你用一个临时的替换它在锁构造函数调用中的用法,你将不需要 try_lock 的外部声明:

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

否则编译器会将 try_lock 的拷贝传递给您的构造函数,此时它会想要链接到它。

当标准库需要这样做时,它使用constexpr:

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

关于c++ - 如何正确使用标签调度来选择构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20775285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com