Reputation: 69
Let's say my program consists of two components trusted and untrusted. I would like to have to code class A's declaration only once but in two different namespaces, but their implementation can be different based on the namespace with only coding the common API once. I do not want to use macros for implementations like #ifdef UNTRSUTED
.etc.
I do not want to use abstractions and inheritance to achieve different behavior. I'm just curious if it's possible.
In the header A.h I will have
// A.h
#pragma once
namespace app {
// I know I can't get what I want with naming the same namespace twice
namespace untrusted, trusted {
class A {
doDifferentFoo();
doCommonBar() // this one is common between two impls;
}
}
}
And in the implementation, I will have A-common.cpp (to implement common interface for both namespaces only once), A-untrusted.cpp (to implement doDifferentFoo for untrusted namespace) and A-trusted.cpp (to implement doDifferentFoo for trusted namespace)
Upvotes: 1
Views: 70
Reputation: 3929
// A.h
class A {
void doDifferentFoo();
void doCommonBar()
{ // ...
}
};
// A_trusted.h
namespace app
{
namespace trusted
{
#include "A.h"
void A::doDifferentFoo() // can be moved to cpp-file if needed/wanted
{
}
}
}
// A_untrusted.h
namespace app
{
namespace untrusted
{
#include "A.h"
void A::doDifferentFoo() // can be moved to cpp-file if needed/wanted
{
}
}
}
Upvotes: 0
Reputation: 22152
I guess the simplest way to do this, is to move the common declarations into an extra file and then include it twice:
A_detail.h:
// No `#pragma once` here!
class A {
doDifferentFoo();
doCommonBar(); // this one is common between two impls;
};
A.h:
#pragma once
namespace app {
namespace trusted {
#include "a_detail.h"
}
namespace untrusted {
#include "a_detail.h"
}
}
A-untrusted.cpp:
#include "a.h"
namespace app { namespace untrusted {
// ...
} }
A-trusted.cpp:
#include "a.h"
namespace app { namespace trusted {
// ...
} }
A-common_detail.cpp (maybe choose different file ending; should not be compiled as translation unit):
// common definitions/declarations without `namespace`
A-common.cpp:
namespace app {
namespace untrusted {
#include "A-common_detail.cpp"
}
namespace trusted {
#include "A-common_detail.cpp"
}
}
I am not sure that this is worth it. Alternatively you could (in each file with common code) use a macro for all common code and call that twice for the two namespaces. However you did say that you didn't want to use macros.
There is no way to do this without the help of the preprocessor, because every declaration (with only one declarator) declares exactly one name in one scope.
Upvotes: 1