Goal
My objective is to call StaticLibrary::func()
from the property (unnamed class) on Environment using the dot syntax.
For example:
env.bar.func();
I have been able to achieve static_cast<StaticLibrary>(env.bar).func();
, which is close, but the syntax is still too cumbersome.
Question
Can the static cast be inferred, or can I overload some operator to get the desired syntax?
NOTE: I have a constraint that I cannot put
StaticLibrary
directly as a public member of theEnvironment
class (object, reference or pointer).
Error
I currently get the error (which I understand, but pasted here for completeness):
unnamedDotSyntax.cpp: In function ‘int main()’:
unnamedDotSyntax.cpp:48:13: error: ‘class Environment::<anonymous>’ has no member named ‘func’
env.bar.func();
^
Code
The example below is the most distilled version of the code I can offer.
#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();
}
NOTE: This must be GCC compatible not Microsoft VC++