我正在尝试编写一个接受可变参数“对列表”的模板。“对”将是一种类型,然后是一种尺寸。
我写了一些有效的东西:
#include <cstddef>
#include <iostream>
template <typename T, size_t N>
class DeferPair
{
using Type = T;
static constexpr size_t kSize = N;
public:
void defer(const T& e)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
//Defer this specific type into a fixed-length/statically-allocated queue
//Discard oldest if the queue is already full
}
};
template <typename... Pairs>
class Defer;
template <typename Pair, typename... RemainingPairs>
class Defer<Pair, RemainingPairs...> : public Pair, public Defer<RemainingPairs...>
{
public:
using Pair::defer;
using Defer<RemainingPairs...>::defer;
};
template <typename …
Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何将可变参数移动(或者如果移动不可用,则仅将其复制)到模板化函数中的 lambda 中。
我正在使用仅移动类(见下文)对此进行测试,因为这将是需要与我的模板一起使用的“最坏情况”。
class MoveOnlyTest {
public:
MoveOnlyTest(int a, int b = 20, int c = 30) : _a(a), _b(b), _c(c) {
std::cout << "MoveOnlyTest: Constructor" << std::endl;
}
~MoveOnlyTest() {
std::cout << "MoveOnlyTest: Destructor" << std::endl;
}
MoveOnlyTest(const MoveOnlyTest& other) = delete;
MoveOnlyTest(MoveOnlyTest&& other) :
_a(std::move(other._a)),
_b(std::move(other._b)),
_c(std::move(other._c))
{
std::cout << "MoveOnlyTest: Move Constructor" << std::endl;
other._a = 0;
other._b = 0;
other._c = 0;
}
MoveOnlyTest& operator=(const MoveOnlyTest& other) = delete;
MoveOnlyTest& operator=(MoveOnlyTest&& other) {
if (this …
Run Code Online (Sandbox Code Playgroud) 如果我有这样的模板:
template <typename ... TYPES>
class Visitor {
public:
//virtual void visit(...) {}
};
Run Code Online (Sandbox Code Playgroud)
有没有办法让 C++ 为列表中的“每个”类型生成虚拟方法?
例如,从概念上讲,我想
class A;
class B;
class C;
class MyVisitor : public Visitor<A,B,C>;
Run Code Online (Sandbox Code Playgroud)
具有以下虚拟方法
virtual void visit(const A&) {}
virtual void visit(const B&) {}
virtual void visit(const C&) {}
Run Code Online (Sandbox Code Playgroud) 从std::shared_ptr 线程安全等文章中,我知道 std::shared_ptr 的控制块按标准保证是线程安全的,而指向的实际数据本质上不是线程安全的(即,它是对我来说,作为用户,做到这一点)。
我在研究中未能找到如何保证这一点的答案。我的意思是,具体使用什么机制来确保控制块是线程安全的(因此对象只被删除一次)?
我问这个问题是因为我正在将 newlib-nano C++ 库与 FreeRTOS 一起用于嵌入式系统。这两者本质上并不是为了相互协作而设计的。由于我从未编写过任何代码来确保控制块是线程安全的(例如,没有关键部分或互斥体的代码),因此我只能假设它实际上可能不是 FreeRTOS 线程安全的。