gpt4 book ai didi

C++ boost::bind 说不可访问的基类

转载 作者:太空狗 更新时间:2023-10-29 23:30:29 34 4
gpt4 key购买 nike

我正在尝试使用 boost::bind 调用类中的成员函数。通常这工作正常,但在这种特殊情况下,我的编译器 (GCC) 提示我试图使用不可访问的基类,而我不是。

下面是一些演示问题的代码。我做错了什么?

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>

class base
{
protected:
void test()
{
std::cout << "base::test()\n";
}
};

class derived: virtual protected base
{
public:
using base::test;
};

int main(void)
{
derived d;

// This works, calling derived::test(), which in turn calls base::test()
d.test();

// This does not work, saying 'base' is an inaccessible base of 'derived',
// but I am not binding base::test, I am binding derived::test.
boost::function<void()> fn;
fn = boost::bind(&derived::test, d);
fn();

return 0;
}

最佳答案

using 声明没有定义函数。它“声明一个名称”(不是函数!),并取消隐藏基本名称。声明本身确实有其自己的可访问性级别,这就是您首先使用它的原因,但再次强调:using 声明不声明新的成员函数。例如。 C++11 7.3.3/11:

The entity declared by a using-declaration shall be known in the context using it according to its definition at the point of the using-declaration.

在您的例子中,“它的定义”仍然是 void base::test(){}that 是派生的已知实体类并由 &derived::test 引用。您无法从中获取 void(derived:**)() 类型的函数指针,因为没有这样的函数。

当您说 &derived::test 时,将使用 & 运算符,其工作方式如下 (5.3.1/3):

The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. If the operand is a qualified-id naming a non-static member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C::m.

在我对上述逻辑的解释中,&derived::test“命名类base 的非静态成员test”。 [感谢@DyP:] 在 10.2/3 中正式化:

The lookup set for f in C [...] consists of [...] the declaration set [...]. In the declaration set, using-declarations are replaced by the members they designate

如果你真的想要,你可以像这样提供一个包装器:

class derived : protected base
{
public:
void test() { base::test(); }
};

(奇怪的是,该解决方案实际上确实隐藏了我们想要的基函数。我们没有使用using,而是使用明确限定的名称来引用基函数。)

关于C++ boost::bind 说不可访问的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19340190/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com