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

时间:2015-04-23 19:58:15

标签: c++ this

#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;
}

我希望通过引用this指向Bar上模板化的类Foo来传递this指针。如果我不想在构建bar时取消引用********************************************************************* # command 1 ********************************************************************* Object column1 column2 Total ------------------------------------------------------------------- object 1 526 9484 10010 object 2 2 10008 10010 Object 3 0 20000 20000 ********************************************************************* # command 2 ********************************************************************* (... tabular data ...) ,那么该语法是什么?

ideone链接:http://ideone.com/jGviBM

1 个答案:

答案 0 :(得分:1)

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

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

    private:
     C& _c;
};

您也可以单独Bar类/更改当前类以保持指针而不是引用,如πάντα ῥεῖ指出的那样。

相关问题