标准库类模板std::bitset<N>有一个构造函数(C++ 11及更高版本,unsigned longC++ 11之前的参数)
constexpr bitset(unsigned long long) noexcept
Run Code Online (Sandbox Code Playgroud)
与许多最佳实践指南相反,此单参数构造函数未标记为explicit.这背后的理由是什么?
c++ explicit-constructor unsigned-long-long-int bitset implicit-conversion
考虑重载加法运算的遗留类模板+=和+
template<class T>
class X
{
public:
X() = default;
/* implicict */ X(T v): val(v) {}
X<T>& operator+=(X<T> const& rhs) { val += rhs.val; return *this; }
X<T> operator+ (X<T> const& rhs) const { return X<T>(*this) += rhs; }
private:
T val;
};
Run Code Online (Sandbox Code Playgroud)
在代码审查时,观察到它+是可实现的+=,为什么不使它成为非成员(并保证左右参数的对称性)?
template<class T>
class X
{
public:
X() = default;
/* implicit */ X(T v): val(v) {}
X<T>& operator+=(X<T> const& rhs) { val += rhs.val; return *this; }
private: …Run Code Online (Sandbox Code Playgroud) c++ operator-overloading implicit-conversion argument-dependent-lookup non-member-functions