std :: reference_wrapper和多态容器 [英] std::reference_wrapper and polymorphic containers
问题描述
我正在尝试使用std::reference_wrapper
为这些类创建多态向量:
I am trying to make a polymorphic vector using std::reference_wrapper
for these classes:
struct Int2TypeBase{
virtual void which(){ std::cout << "Int2TypeBase" << "\n";}
};
template <int v>
struct Int2Type : public Int2TypeBase
{
enum
{
value = v
};
void which(){ std::cout << "Int2Type<" << value << ">""\n";}
friend bool operator==(const Int2Type& lhs, const Int2Type& rhs){
return lhs.v == rhs.v;
}
};
现在,我正在尝试像这样使用std::reference_wrapper
:
Now I am trying to make use of std::reference_wrapper
like this:
int main(){
using namespace std;
std::vector<std::reference_wrapper<Int2TypeBase>> v;
Int2Type<0> i2t_1;
v.emplace_back(i2t_1);
auto x = v[0];
x.get().which();
std::cout << typeid(x.get()).name() << "\n";
// std::cout << (x.get() == i2t_1) << "\n";
}
输出为:
Int2Type<0>
8Int2TypeILi0EE
这就是我所期望的.
现在,当我取消注释std::cout << (x.get() == i2t_1) << "\n";
时,我会得到
Now however, when I uncomment std::cout << (x.get() == i2t_1) << "\n";
I will get
invalid operands to binary expression ('Int2TypeBase' and 'Int2Type<0>')
这使我感到困惑,因为typeid(x.get()).name()
返回了8Int2TypeILi0EE
而不是F12Int2TypeBasevE
,这是我从typeid(Int2TypeBase()).name();
获得的结果.此外,还为派生类调用了which()
...那么为什么x.get() == i2t_1
中的x.get()
求值为Int2TypeBase
?
This confuses me, as typeid(x.get()).name()
returned 8Int2TypeILi0EE
rather than F12Int2TypeBasevE
which is what I get for typeid(Int2TypeBase()).name();
. Furthermore which()
also was called for the derived class... so then why does x.get()
in x.get() == i2t_1
evaluate to a Int2TypeBase
?
推荐答案
在编译时,编译器只能告诉x.get()的类型为Int2TypeBase,因为如声明的那样,您可以在其中放置任何Int2TypeBase.因此,在编译时,无法确定==运算符是否可以工作.
At compile time, the compiler can only tell that the type of x.get() is Int2TypeBase, because as declared you can put any Int2TypeBase there. So at compile time, it can't determine that the == operator will work.
在运行时,您放入集合中的对象将引用其完整类型,因此typeid返回您期望的值,并调用正确的虚函数.
At run time, the objects you put in the collection reference their full type, so typeid returns what you expect and the correct virtual function is called.
这篇关于std :: reference_wrapper和多态容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!