I'm trying to access some private members of a class that's part of an API that I do not have the ability to change.
Listing 1: api.h
namespace api {
class Bar;
class Foo {
public:
const int& getSecret() const { return secretValue; }
private:
int secretValue;
friend class Bar;
};
}
Listing 2: program.cpp
#include <iostream>
#include "api.h"
namespace {
class api::Bar {
public:
void touchFooSecretly(api::Foo& f) { f.secretValue = 42; }
};
}
int main()
{
api::Foo f;
api::Bar b;
b.touchFooSecretly(f);
std::cout << f.getSecret() << std::endl; // 42 (Solaris)
return 0;
}
This compiles (and runs) fine in Oracle Solaris Studio 12.3, but clang and g++ (understandably) have a problem with it:
program.cpp:5:13: error: cannot define or redeclare 'Bar' here because namespace '' does not enclose namespace 'api'
This hack is currently being employed for the sake of efficiency, with good knowledge of how the class operates internally. Is there a way to achieve a similar trick in clang such that I can change the meaning of a friend class for my translation unit alone?
Or, failing that, any trick that lets me access a private member in a class where I cannot modify the declarations would be appreciated!