将此指针传递给模板化成员变量

Passing this pointer to a templated member variable

#include <iostream>
using namespace std;

template<class C>
class Bar
{
    public:
     Bar(C& c) : _c(c) {};
     ~Bar(){};

    private:
     C& _c;
};

class Foo
{
    public:
     Foo() : bar(this) {}; //instead of bar(*this)
     ~Foo(){};

    private:
     Bar<Foo> bar;
};


int main() {
    // your code goes here
    Foo f;
    return 0;
}

我想通过引用 Foo 上模板化的 class Bar 来传递 this 指针。如果我不想在构建 bar 时取消引用 this,语法是什么?

ideone link: http://ideone.com/jGviBM

您必须创建一个接受 C * 的构造函数,但无论哪种方式,您都必须取消引用指针:

template<class C>
class Bar
{
    public:
     Bar(C& c) : _c(c) {};
     Bar(C* c) : _c(*c) {};
     ~Bar(){};

    private:
     C& _c;
};

您也可以创建一个单独的 Bar class/change 您当前的 class 来保存指针而不是引用,正如 πάντα ῥεῖ 指出的那样。