使用C++ 14,我们可以将一些关联容器(如std :: set)的元素与存储在容器中的其他类型进行比较.当比较器is_transparent表示为一种类型时,它应该起作用(参见例如std :: set :: find).
假设我有一个字符串包装器,它对字符串执行一些检查(如果它的格式是有效格式等等 - 不是很重要,但构造它足够重,我想避免它+它可以抛出异常)并且它是存储在std :: set中以具有唯一值的容器.我该如何为它写一个比较器?它应该像下面那样吗?我能超载并使用我sw::operator<()来实现同样的目标吗?
class sw
{
public:
explicit sw(const std::string& s) : s_(s) { /* dragons be here */ }
const std::string& getString() const { return s_; }
bool operator<(const sw& other) const { return s_ < other.s_; }
private:
std::string s_;
};
struct Comparator
{
using is_transparent = std::true_type;
bool operator()(const sw& lhs, const std::string& rhs) const { return lhs.getString() < rhs; } …Run Code Online (Sandbox Code Playgroud) 我正在编写一个简单的Python库,其中我有几个以下划线开头的"私有"函数:
def _a():
pass
def _b():
pass
def public_interface_call():
_a()
_b()
Run Code Online (Sandbox Code Playgroud)
这样我的库用户可以简单地做,from MyLib.Module import *并且他们的命名空间不会与实现细节混杂在一起.
然而,我也在编写单元测试,我很乐意分别测试这些函数,简单地导入我模块中的所有符号都非常方便.目前我在做,from Mylib.Module import _a _b public_interface_call但我想知道是否有更好/更快/更清洁的方式来实现我想要的?
你们知道是否存在与 C++ 中的 boost::optional 等效的 Python(或自 C++11 以来的 std::optional :http : //en.cppreference.com/w/cpp/utility/optional),即处理语义可选变量的库?
我知道如何自己实现它或使用其他解决方案(比如foo = (bar, True)我觉得丑陋和不可读)。只是好奇是否有现有的解决方案。