【发布时间】:2011-09-12 20:56:04
【问题描述】:
A 是基类,B 是继承类。 A 从与 boost::bind+boost::function 绑定的 B 中获取成员函数指针,以便稍后从其他基类函数存储和执行。 A 和 B 类位于不同的包含文件中。我想限制从 A 实现继承类的开发人员,继承类中的绑定成员函数指针是私有函数。环境为C++、gcc 4.x和Linux。
示例:
------ INCLUDE FILE -----
#include <boost/bind.hpp>
#include <boost/function.hpp>
struct A
{
protected:
void Register(const char* name, boost::function<void()> FuncPtr)
{
// (I am not intended to pass the name argument, but probably somebody
// knows something gcc magic which would use it to solve the problem.)
// I want to ensure that FuncPtr points to a private member
// function. What can be known: "B::CalledFunction" string and FuncPtr.
// If it is not a private member function then drop an error message
// during run-time or during compilation (???).
}
};
------ OTHER INCLUDE FILE -----
...
struct B : public A
{
B() : A()
{
Register("B::CalledFunction", boost::bind(&B::CalledFunction, this));
}
private:
void CalledFunction()
{
}
};
在之前/而不是简单地直接调用A::Register() 之前,也可以欣赏任何类型的宏魔术或类似的东西。
【问题讨论】:
-
为什么您要强制执行此操作?
-
在 C++11 中,访问规范的规则被更改为在 SFINAE 之前应用,因此您将有机会进行一些宏 hack 来检测函数是否是私有的。但是我觉得不值得,为什么要设置这样的人为限制?
-
这样做的目的是什么?为什么不按照应有的方式使用继承?
-
目的:在我的情况下,继承的类会实现新的功能,绑定并存储在基类中以便以后调用它们,但我想阻止使用B类的开发人员调用直接绑定这些函数。
-
@kecsap :派生类的成员函数的可访问性不应该取决于派生类的作者吗?为什么基类应该关心这两种方式?
标签: c++ linux gcc private-members