C++备忘录063:Overloading on Universal References gist of "Effective Modern C++"
程序员文章站
2024-02-29 08:20:58
...
Passing by value
Consider passing objects by value when you know you’ll copy them
struct S {
S(std::string n) { // replace T&& ctor
: name(std::move(n)) {}
std::string name;
};
Use Tag dispatch
struct S {
template <typename T, typename std::enable_if_t<
!std::is_same_v<S, std::decay_t<T>>>
>
S(T&& n);
};
Solving the derived class ctor problem, change it to
struct S {
template <typename T, typename std::enable_if_t<
!std::is_base_of<S, std::decay_t<T>>>
>
S(T&& n);
};
To distinguish it from other constructors
struct S {
template <typename T, typename std::enable_if_t<
!std::is_base_of<Person, std::decay_t<T>>
&&
!std::is_integral<std::remove_reference_t<T>>
>>
S(T&& n): name(std::forward<T>(n)) {
static_cast(std::is_constructible<std::string, T>); // gives a better error message
}
S(int ind): name(foo(idx)) {}
std::string name;
};