【发布时间】:2021-02-04 20:49:44
【问题描述】:
如果您的对象有多个参数并且可以采用 l 或 r 值引用,则构造函数的数量会快速跳跃。一些模板技巧可以简化情况吗?或者这是否会导致我不知道的问题,或者我是否过度思考并且有标准的方法来简化它?
// In the following context I using std::string as an example o
// something that can be moved or copied, where we would prefer
// a move rather than a copy.
// With just two parameters.
// I need 4 constructors to do the correct thing (copy/move) correctly.
class Original
{
std::string val1;
std::string val2;
public:
Original(std::string const& v1, std::string const& v2): val1(v1), val2(v2) {}
Original(std::string const& v1, std::string&& v2): val1(v1), val2(std::move(v2)) {}
Original(std::string&& v1, std::string const& v2): val1(std::move(v1)), val2(v2) {}
Original(std::string&& v1, std::string&& v2): val1(std::move(v1)), val2(std::move(v2)) {}
};
如果参数类型是模板,我可以使用完美转发。
// This is a check to see if a template is the specific class.
// Or can be trivially constructed from the parameters.
template<typename Actual>
using ValidString = std::enable_if_t<std::is_trivially_constructible_v<std::string, Actual>, bool>;
// With these I can simplify my requirement of 4 constructors
// and simplify to a single templaed constructor that can do perfect forwarding.
class Alternative
{
std::string val1;
std::string val2;
public:
template<typename V1, typename V2, ValidString<V1> = true, ValidString<V2> = true>
Original(V1 v1, V2 v2): val1(std::forward<V1>(v1)), val2(std::forward<V2>(v2)) {}
};
两个问题:
- 是否已经有一种技术可以完美转发我错过的参数?
- 如果没有当前技术,这里有什么问题?
【问题讨论】:
-
你可能会喜欢 Herb Sutter 的 this 视频