简体   繁体   English

与class一起使用std :: reference_wrapper时编译错误“没有成员命名”

[英]compile error with std::reference_wrapper “has no member named” when used with class

So I've found this fancy stuff std::reference_wrapper in C++11 which I found could be useful in future program development. 所以我在C ++ 11中发现了这个花哨的东西std::reference_wrapper ,我发现它在将来的程序开发中很有用。 I played with it for a bit and I thought it could replace good-old reference in some cases for better usage, until I bumped into the following error: 我玩了一会儿,我认为它可以在某些情况下取代旧的参考以便更好地使用,直到我碰到以下错误:

#include <iostream>
#include <functional>

class testbench {
public:
    int ownerid = 5;
    bool camper = false;
};

class testing {
public:
    testing(testbench &x);
    int quack = 3;
    std::reference_wrapper <testbench> camper;
};

testing::testing(testbench &x):camper(x) {
}

int main() {
    testbench tempo;
    testing test_a (tempo);
    std::cout << test_a.camper.ownerid;
}

this would cause an error in gcc (I'm using Code::Blocks as Editor and gcc as compiler) 这会导致gcc中的错误(我使用Code :: Blocks作为编辑器,gcc作为编译器使用)

'class std::reference_wrapper<testbench>' has no member named 'ownerid'

If the line 如果行

    std::reference_wrapper <testbench> camper;

is changed to : 改为:

    testbench &camper;

Then everything is worked as I expected. 然后一切都按照我的预期运作。

How do I fix this, or is it just my misunderstanding std::reference_wrapper as a general improvement of reference? 我该如何解决这个问题,还是只是我误解了std::reference_wrapper作为std::reference_wrapper的一般改进?

Your understanding is wrong. 你的理解是错误的。 std::reference_wrapper can implicitly cast to a T& (in your case, testbench) but when you use the member accessor ( test_a.camper.ownerid ) it's operating on the camper , not the object it's wrapping. std::reference_wrapper可以隐式转换为T&(在你的情况下,测试平台),但是当你使用成员访问( test_a.camper.ownerid )它的操作camper ,不是对象它的包装。

You can either do a cast or use the get member function. 您可以执行强制转换或使用get成员函数。 This is untested, but I think it'll work: 这是未经测试的,但我认为它会起作用:

test_a.camper.get().ownerid;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM