在c++ 11中声明多参数构造函数的最佳方式是什么?

What is the best way to declare multiple argument constructor in C++11

本文关键字:最佳 方式 是什么 构造函数 参数 c++ 声明      更新时间:2023-10-16

当创建像这样的类时:

class Test {
 public:
   ...
private:
   string s1_;
   string s2_;
   vector<int> v_;
};
声明一个接受两个字符串和一个向量的构造函数的最好方法是什么?更具体地说,如何处理左值和右值引用?

我看到以下三个选项:

  1. 创建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)}
       {
          ...
       }
    

    优点:每一种可能性都被有效地处理了。

    缺点:需要大量的代码来处理每个组合,并且可能容易出错。

  2. 总是复制和移动参数:

       Test(string s1, string s2, vector<int> v) :
          s1_{move(s1)}, s2_{move(s2)}, v_{move(v)}
       {
          ...
       }
    

    优点:只有一个演员。

    缺点:效率不高,因为移动并不意味着自由。

  3. 使用"通用引用":

       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))
{}