目标
我的目标是StaticLibrary::func()
使用点语法从 Environment 的属性(未命名的类)中调用。
例如:
env.bar.func();
我已经能够实现static_cast<StaticLibrary>(env.bar).func();
,很接近了,但是语法还是太繁琐了。
问题
可以推断出静态转换,还是可以重载某些运算符以获得所需的语法?
注意:我有一个不能
StaticLibrary
直接作为Environment
类的公共成员(对象、引用或指针)的约束。
错误
我目前收到错误(我理解,但为了完整起见粘贴在这里):
unnamedDotSyntax.cpp: In function ‘int main()’:
unnamedDotSyntax.cpp:48:13: error: ‘class Environment::<anonymous>’ has no member named ‘func’
env.bar.func();
^
代码
下面的示例是我能提供的最精炼的代码版本。
#include <iostream>
class StaticLibrary {
public:
int func (void) {
std::cout << "called " << __FUNCTION__ << std::endl;
}
};
class Environment {
public:
Environment (void) {
bar.sl = &sl;
}
inline
int foo (void) {
std::cout << "called " << __FUNCTION__ << std::endl;
}
class {
friend Environment;
public:
operator StaticLibrary & (void) {
return *sl;
}
private:
StaticLibrary * sl;
} bar;
private:
StaticLibrary sl;
};
int main (void) {
Environment env;
env.foo();
// Works
StaticLibrary sl = env.bar;
sl.func();
// Works, but the syntax is too cumbersome. Can the static cast be inferred somehow?
static_cast<StaticLibrary>(env.bar).func();
// unnamedDotSyntax.cpp:48:13: error: ‘class Environment::<anonymous>’ has no member named ‘func’
// env.bar.func();
env.bar.func();
}
注意:这必须与 GCC 兼容,而不是 Microsoft VC++