【问题标题】:How do I implement "perfect forwarding" in a class template?如何在类模板中实现“完美转发”?
【发布时间】:2013-11-17 11:59:13
【问题描述】:

我有一个带有模板参数 T 的类模板和一个类型为 T 的成员。我想用传递给 ctor 的参数初始化该成员,并且如果传递的参数是右值引用并且 T支持移动语义:

template <typename T>
class C {
public:
    explicit C(T t) : t_(t)
    {
    }

    explicit C(T&& t) : t_(std::move(t))
    {
    }

    ...

 private:    
    T t_;
 };

如果我尝试将右值引用传递给 ctor,g++ 4.8 会出现以下错误:

int main()
{
    int x = 0;
    C<int> p1{x}; // OK
    C<int> p2{1}; // error g++-4.8: call of overloaded ‘C(<brace-enclosed initializer list>)’ is ambiguous
    return 0;
}

完整的错误文本:

g++-4.8 -std=c++11 -O2 -Wall -pedantic -pthread main.cpp
    main.cpp:在函数“int main()”中:
    main.cpp:23:16:错误:重载“C()”的调用不明确
    C p2{1}; // 错误 g++-4.8:重载“C()”的调用不明确
              ^
    main.cpp:23:16: 注意:候选人是:
    main.cpp:12:11:注意:C::C(T&&) [with T = int]
      显式 C(T&& t) : t_(std::move(t))
               ^
    main.cpp:8:14:注意:C::C(T) [with T = int]
     显式 C(T t) : t_(t)
              ^
    main.cpp:6:7: 注意:constexpr C::C(const C&)
     C类{
           ^
    main.cpp:6:7: 注意:constexpr C::C(C&&)

有人可以帮帮我吗? 谢谢!

【问题讨论】:

  • 只要explicit C(T t) : t_(std::move(t)) { }。这几乎是完美的。

标签: c++ templates c++11


【解决方案1】:

我通过在 C(T t) const 引用中设置参数 t 解决了这个问题。

【讨论】:

  • 尝试以下操作:template&lt; typename T &gt; explicit C(T &amp;&amp; t) : t_(std::forward&lt; T &gt;(t)) { ; }.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 2012-01-06
  • 1970-01-01
  • 2011-09-23
相关资源
最近更新 更多