从各种来源(例如here)我知道嵌套类应该能够看到封闭类的所有成员,根据C ++ 11标准。
尽管如此,我遇到了以下类层次结构,它不能用Clang编译。
#include <iostream>
#include <vector>
class BaseEnclosing
{
public :
BaseEnclosing(double bar) { m_parameters.push_back(bar); }
virtual void DoSomething() = 0;
virtual ~BaseEnclosing() {}
protected :
std::vector<double> m_parameters;
template<class T>
class BaseNested
{
public :
BaseNested(BaseEnclosing * baseEncPtr) : m_baseEncPtr(baseEncPtr) {}
virtual void operator()(T param) const = 0;
virtual ~BaseNested() {}
protected:
BaseEnclosing * m_baseEncPtr;
};
};
class DerivedEnclosing : public BaseEnclosing
{
public :
DerivedEnclosing(double bar) : BaseEnclosing(bar) {}
void DoSomething()
{
// call some library functions which use the functor of DerivedNested and pass DerivedNested(this)
}
virtual ~DerivedEnclosing() {}
protected :
class DerivedNested : public BaseNested<std::vector<double>>
{
public :
DerivedNested(BaseEnclosing * baseEncPtr) : BaseNested(baseEncPtr) {}
void operator()(std::vector<double> myContainer) const override
{
//error: 'm_parameters' is a protected member of 'BaseEnclosing'
//can only access this member on an object of type 'DerivedEnclosing'
double retrieved_bar = m_baseEncPtr->m_parameters.back(); // <---------- ERROR
// do something with myContainer and retrieved_bar
}
virtual ~DerivedNested() {}
};
};
int main()
{
DerivedEnclosing test (42.5);
test.DoSomething();
return 0;
}
根据我的理解,DerivedEnclosing
应该继承m_parameters
,因此我希望DerivedNested
的方法可以看到它。
为了更好地理解我的意图,我正在尝试使用Boost Odeint,它需要将方程的右侧指定为functor的函数指针。我决定使用DoSomething()
中的第二个选项。
我的设计需要BaseEnclosing
和DerivedEnclosing
用于其他目的,嵌套类并不是完全需要的,但听起来是一个很好的方法。