我想创建一个shared_ptr内容比较函子来代替std::less<T>关联容器和std算法.我已经看到了几个使用以下(或类似)模型的自定义比较器示例:
template <typename T>
struct SharedPtrContentsLess {
bool operator()(const boost::shared_ptr<T>& lhs,
const boost::shared_ptr<T> rhs) const {
return std::less<T>(*lhs, *rhs);
//or: return (*lhs) < (*rhs);
}
//defining these here instead of using std::binary_functor (C++11 deprecated)
typedef boost::shared_ptr<T> first_argument_type;
typedef boost::shared_ptr<T> second_argument_type;
typedef bool return_type;
};
Run Code Online (Sandbox Code Playgroud)
但为什么我不想延伸std::less呢?像这样:
template <typename T>
struct SharedPtrContentsLess : public std::less< boost:shared_ptr<T> > {
bool operator()(const boost::shared_ptr<T>& lhs,
const boost::shared_ptr<T> rhs) const {
return std::less<T>(*lhs, *rhs);
}
};
Run Code Online (Sandbox Code Playgroud)
这给我买了什么吗?
我认为这会让我typedef免费获得s,就好像我正在扩展已弃用的那样std::binary_function.在C++ …
我有一堆使用硬件(FPGA)寄存器的代码,其大致形式如下:
struct SomeRegFields {
unsigned int lower : 16;
unsigned int upper : 16;
};
union SomeReg {
uint32_t wholeReg;
SomeRegFields fields;
};
Run Code Online (Sandbox Code Playgroud)
(这些寄存器类型中的大多数都比较复杂。这是说明性的。)
在清理一堆通过以下方式设置寄存器的代码时:
SomeReg reg1;
reg1.wholeReg = 0;
// ... assign individual fields
card->writeReg(REG1_ADDRESS, reg1.wholeReg);
SomeReg reg2;
reg2.wholeReg = card->readReg(REG2_ADDRESS);
// ... do something with reg2 field values
Run Code Online (Sandbox Code Playgroud)
我有点心不在焉,不小心得到了以下结果:
SomeReg reg1{ reg1.wholeReg = 0 };
SomeReg reg2{ reg2.wholeReg = card->readReg(REG2_ADDRESS) };
Run Code Online (Sandbox Code Playgroud)
当然,该reg1.wholeReg =部分是错误的,应该删除。
让我烦恼的是它可以在 MSVC 和 GCC 上编译。我预计这里会出现语法错误。此外,有时它工作正常,并且值实际上被正确复制/分配,但其他时候,即使返回的寄存器值非 0,它也会导致 0 值。它是不可预测的,但在哪些情况有效和哪些情况无效的运行之间似乎是一致的。
知道为什么编译器不将其标记为错误语法,以及为什么它在某些情况下似乎有效但在其他情况下会中断?当然,我认为这是未定义的行为,但为什么它会改变通常看起来几乎相同的调用(通常是背靠背)之间的行为? …