在c++ 11中声明多参数构造函数的最佳方式是什么?
What is the best way to declare multiple argument constructor in C++11
当创建像这样的类时:
class Test {
public:
...
private:
string s1_;
string s2_;
vector<int> v_;
};
声明一个接受两个字符串和一个向量的构造函数的最好方法是什么?更具体地说,如何处理左值和右值引用?我看到以下三个选项:
创建lvref和rvref:
Test(const string& s1, const string& s2, const vector<int>& v) : s1_{s1}, s2_{s2}, v_{v} { ... } Test(const string& s1, const string& s2, vector<int>&& v) : s1_{s1}, s2_{s2}, v_{move(v)} { ... } Test(const string& s1, string&& s2, const vector<int>& v) : s1_{s1}, s2_{move(s2)}, v_{v} { ... } Test(const string& s1, string&& s2, vector<int>&& v) : s1_{s1}, s2_{move(s2)}, v_{move(v)} { ... } Test(string&& s1, const string& s2, const vector<int>& v) : s1_{move(s1)}, s2_{s2}, v_{v} { ... } Test(string&& s1, const string& s2, vector<int>&& v) : s1_{move(s1)}, s2_{s2}, v_{move(v)} { ... } Test(string&& s1, string&& s2, const vector<int>& v) : s1_{move(s1)}, s2_{move(s2)}, v_{v} { ... } Test(string&& s1, string&& s2, vector<int>&& v) : s1_{move(s1)}, s2_{move(s2)}, v_{move(v)} { ... }
优点:每一种可能性都被有效地处理了。
缺点:需要大量的代码来处理每个组合,并且可能容易出错。
总是复制和移动参数:
Test(string s1, string s2, vector<int> v) : s1_{move(s1)}, s2_{move(s2)}, v_{move(v)} { ... }
优点:只有一个演员。
缺点:效率不高,因为移动并不意味着自由。
使用"通用引用":
template <typename S1, typename S2, typename V> Test(S1&& s1, S2&& s2, V&& v) : s1_{forward<S1>(s1)}, s2_{forward<S2>(s2)}, v_{forward<V>(v)} { ... }
优点:一个元素可以有效地处理所有事情。
缺点:没有意义。s1 s2 v是什么?甚至更容易出错(例如
Test error{1,2,3}
编译)。
有更好的方法来实现这一点吗?
怎么样:
template <typename String, typename VectorInt>
Test(String &&s1, String &&s2, VectorInt &&v,
typename std::enable_if<std::is_same<typename std::decay<String>::type,std::string>::value &&
std::is_same<typename std::decay<VectorInt>::type,std::vector<int>>::value>::type * = nullptr) :
s1_(std::forward<String>(s1)), s2_(std::forward<String>(s2)),
v_(std::forward<VectorInt>(v))
{}
相关文章:
- 在c代码之间共享数据的最佳方式
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 在reactor中存储eventHandlers的最佳方式是什么
- 在AVX通道中混洗的最佳方式
- 从 T 创建 std::future 的最佳方式<T>
- C++:使用 std::unique_ptr 访问重载运算符++的最佳方式?
- 对列表列表中的元素进行分组的最佳方式
- 利用 GPU 的最佳方式
- 使用 QT C++过滤大数据的最佳方式
- 算法设计:用边界数字表示 2D 网格的最佳方式,以C++?
- 在C++中共享键值对的最佳方式
- 为Catch2中的外部文本文件指定路径的最佳方式
- 代表Quarto棋盘游戏棋子的最佳方式
- 等待线程的最佳方式是什么
- 将uint8_t*buffer和size_tbufferlen从C++传递到C中的API函数的最佳方式是什么
- 创建控制台菜单C++的最佳方式
- 只显示片段着色器的最佳方式是什么
- 复制文件的最佳方式是什么,以便我可以在复制过程中轻松取消复制?