【发布时间】: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)) { }。这几乎是完美的。