基于以下answer https://stackoverflow.com/questions/27536395/passing-pointer-to-member-func-of-outer-class-template-to-nested-class/27536576#27536576到最近的question https://stackoverflow.com/questions/27536395/passing-pointer-to-member-func-of-outer-class-template-to-nested-class,我可以使用函数指针来调用私有方法Foo<T>::foo()
来自另一个班级Bar
,如下所示(另见ideone http://ideone.com/IDsmgY)
#include <iostream>
template<typename T>
struct Bar
{
typedef void (T::*F)();
Bar( T& t_ , F f ) : t( t_ ) , func( f )
{
}
void operator()()
{
(t.*func)();
}
F func;
T& t;
};
template<typename T>
class Foo
{
private:
void foo()
{
std::cout << "Foo<T>::foo()" << std::endl;
}
public:
Foo() : bar( *this , &Foo::foo )
{
bar();
}
Bar<Foo<T> > bar;
};
int main()
{
Foo<int> foo;
}
这适用于 MSVC 2013 和 GCC 4.8.3。有效吗?
C++ 标准说
11.1 类的成员可以是
(1.1)——私人;也就是说,它的名称只能由声明它的类的成员和友元使用。
即访问说明符应用于名称,而不是可执行代码。如果您考虑一下,这是有道理的,因为访问说明符是编译时构造。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)