【发布时间】:2016-09-11 14:41:11
【问题描述】:
是否可以默认传递this?
这是我目前拥有的
class A
{
public:
template<typename T>
void dowithT(T t) {}
};
class B
{
public:
A a;
B()
{
//Calling 'dowithT' with 'this'
a.dowithT(this);
}
};
这个函数每次都需要从函数调用者那里传递this。所以想知道有没有办法封装这个任务,这样就不用把this传给dowithT了。
我试图做这样的事情:
class A
{
public:
// '= this' doesn't compile
template<typename T>
void dowithT(T t = this) {}
};
class B
{
public:
A a;
B()
{
//Calling 'dowithT' without 'this'
a.dowithT();
}
};
不幸的是,我不能使用模板,所以我的第一个解决方案不是一个选项。
这可能吗?
编辑:我在下面用我自己的实现给出了一个具体的答案。最后还有一些我想要的细节。
【问题讨论】:
-
您不需要将
this指针作为参数传递。它总是出现在这个类的上下文中。尝试直接使用它。 -
@MukulGupta:有问题的
this用于class B,默认情况下class A不可用。 -
顺便说一句,我认为你应该重新考虑你的班级设计。 “我写了一个类,它需要从函数的调用者那里传递“this”。” - 这听起来真是个坏主意......
-
@Cornstalks:我的错。
-
@Christian Hackl:我使用“this”作为参数,因为我已经封装了创建任务:
function<void()> (std::bind(func, res),其中“res”是“this”指针的含义
标签: c++ parameter-passing this