为什么 std::forward 不能自己推导出模板参数?
Why can't std::forward deduce template parameters on his own?
好的,所以我在玩移动c'tors,我遇到了一个愚蠢的问题,为什么 std::forward 在某些情况下不能推导出它自己的参数(假设不是在继承时),请考虑以下代码:
#include <iostream>
using namespace std;
struct Moveable {
Moveable(){}
Moveable(Moveable const& other) { cout << "Moveable::Copying" << endl;}
Moveable(Moveable&& other) { cout << "Moveable::Moving" << endl;}
};
struct A {
virtual ~A() {}
A(){}
A(A const& other) : m(other.m) { cout << "A::Copying" << endl;}
A(A&& other) : m(forward<Moveable>(other.m)) { cout << "A::Moving" << endl;} // <--- why can't the compiler deduce that forward is templated over Moveable, just by the fact that he received moveable as the input parameter?
Moveable m;
};
struct B : public A {
B(B const& other) : A(other) { cout << "B::Copying" << endl;}
B(B&& other) : A(forward<A>(other)) { cout << "B::Moving" << endl;} //<--- obvious why I need to forward, because I am to tell him to forward it as a parent class
B(){}
};
int _tmain(int argc, _TCHAR* argv[])
{
B b;
cout << "---------------" << endl;
B b2(move(b));
cout << "---------------" << endl;
return 0;
}
看到两个前锋附近的问题,
谢谢
std::forward<T>
的参数类型是std::remove_reference<T>::type&
。假设你传递了一个类型X
的对象,编译器知道std::remove_reference<T>::type
应该是X
的。但是,它如何确定T
?它必须为每个可能的类型(无限集合)实例化std::remove_reference
,以找出哪些类型具有X
type
。这就是为什么在这种情况下无法进行自动类型推断的原因。
相关文章:
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- 为什么 std::function 可以作为 std::not2 的参数?
- 传递给std::function template的template参数究竟代表什么
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 将函数参数"const char*"转换为"std::string_view"是
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 为什么 std::绑定错误参数可以成功?
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- std::vector 没有重载函数的实例与参数列表匹配
- std::span<const T> 作为函数模板中的参数
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 在构造函数中使用可变参数初始化 std::tuple
- 函数对象无法识别它获得的参数(std::set<int>)
- C 11构造函数参数:std ::移动和值或std :: forward and rvalue参考
- std::move 或 std::forward 参数 std::unique_ptr&<T>&
- 错误:不允许使用"C++/ObjC++"使用无效参数"-std=gnu99"
- **编译器错误** - getline() 函数不接受第一个参数"std:ifstream"是什么我的问题?