Matthieu M. brought up a pattern for access-protection in this answer that i'd seen before, but never conciously considered a pattern:
class SomeKey {
friend class Foo;
SomeKey() {}
// possibly make it non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey);
};
Here only a friend of the key class has access to protectedMethod():
class Foo {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
}
};
class Baz {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
}
};
It allows more fine-granular access-control than making Foo a friend of Bar and avoids more complicated proxying patterns.
Does anyone know whether this approach already has a name, i.e., is a known pattern?
Thanks to your other question it looks like this pattern is now known as the "passkey" pattern.
In C++11, it gets even cleaner, because instead of calling
b.protectedMethod(SomeKey());
you can just call:
b.protectedMethod({});
It seems that this idiom like one mentioned in another SO question here. It is called Attorney-Client idiom and described in more details there.
some boring man like me would make the fowllow code:
int FraudKey=0;
b.protectedMethod(reinterpret_cast<SomeKey&>(FraudKey));
Its pretty close to this:
http://minorfs.wordpress.com/2013/01/18/raiicap-pattern-injected-singleton-alternative-for-c/
Basically if you consider a reference to an object of well designed class to be provide the
access control you need to implement any access control policy that actually makes sense, applying this pattern to anything other than the constructor does not seem to make that much sense.
So as the article states, if you use this key in conjunction with those constructors for what
access control might make sense, objects that represent significant parts of scares resources, that in C++ would generally be implemented as RAII objects, than the name RAIICap or RAII-Capability would indeed make sense.
http://www.eros-os.org/essays/capintro.html
Alternatively you could refer to it with a more general name like construct authority.
The implementation in the article is a bit to much main centered, that is, main needs to create all the authority keys. You can extend on it and make it more flexible by adding an additional public constructor for the key itself:
template <typename T>
class construct_authority {
public:
construct_authority(construct_authority<void> const&)
friend int main(int,char **);
private:
construct_authority(){}
};
That way main could delegate the key creation to other parts of the program.
Personally I think the RAIICap name is quite appropriate for the useful part of this pattern.
A while ago I proposed that this simple template above could be added to the standard library.
https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/p_v-aYIvO1E
Unfortunately there are issues with the idea that there can be one main fingerprint that constitutes a computational root, so something like this apparently can't have a place in the standard library. Having said this, at least for the use with the constructor of RAII classes, this pattern seems to be quite useful.
Related
I'm trying to program a genetic algorithm for a project and am having difficulty keeping different functions separate. I've been reading up on policy-based design, and this seems like a solution to the problem, but I don't really understand how to implement it.
I've got an OptimizerHost, which inherits from a SelectionPolicy (to determine what solutions are evaluated) and a FitnessPolicy (to determine the fitness of any given solution). The problem is I can't figure out how the two policies can communicate with one another. The bulk of the algorithm is implemented in the SelectionPolicy, but it still needs to be able to check the fitness of its solutions. The only thing I can think of is to implement the SelectionPolicy algorithm in the OptimizerHost itself, so then it will inherit the things it needs from the FitnessPolicy. But that seems like its missing the point of using policies in the first place. Am I misunderstanding something?
I'm not very familiar with the Policy-Based design principles (sorry) but when I read your problem, I felt like you need something like pure virtual classes (as interfaces) to help you through it.
The thing is, you cannot use something from the other, if it's not previously declared: this is the basic rule. Thus, you need to use and virtual interface to say SelectPolicy that FitnessPolicy has some members to be used. Please follow the example, and change it accordingly to your algortihms-needs.
First: create the interfaces for the SelectionPolicy and the FitnessPolicy
template <class T> class FitnessPolicyBase
{
public:
virtual int Fitness(T fitnessSet); // assuming you have implemented the required classes etc. here - return value can be different of course
...
} // write your other FitnessPolicy stuff here
template <class T> class SelectionPolicyBase
{
public:
virtual T Selector(FitnessPolicyBase<Solution> evaluator, Set<T> selectionSet); // assuming such a set exists here
...
} // write your other selectionpolicy interface here
Now, since we made these classes pure virtual (they have nothing but virtual functions) we cannot use them but only inherit from them. This is precisely what we'll do: The SelectionPolicy class and the FitnessPolicy class will be inheriting from them, respectively:
class SelectionPolicy: public SelectionPolicyBase<Solution> // say, our solutions are of Solution Type...
{
public:
virtual Solution Selector(FitnessPolicyBase<Solution> evaluator, Set<Solution> selectionSet); // return your selected item in this function
...
}
class FitnessPolicy : public FitnessPolicy Base<Solution> // say, our solutions are of SolutionSet Type...
{
public:
virtual int Fitness(Solution set); // return the fitness score here
...
}
Now, our algortihm can run with two types of parameters: SolutionSetBase and FitnessSetBase. Did we really need the xxxBase types at all? Not actually, as long as we have the public interfaces of the SolutionPolicy and FitnessPolicy classes, we could use them; but using this way, we kinda seperated the `logic' from the problem.
Now, our Selection Policy algorithm can take references to the policy classes and then call the required function. Note here that, policy classes can call each others' classes as well. So this is a valid situation now:
virtual Solution SelectionPolicy::Selector(FitnessPolicyBase<Solution> evaluator, Set<T> selectionSet)
{
int score = evaluator.Fitness(selectionSet[0]); //assuming an array type indexing here. Change accordingly to your implementation and comparisons etc.
}
Now, in order for this to work, though, you must have initialized a FitnessPolicy object and pass it to this Selector. Due to upcasting and virtual functions, it will work properly.
Please forgive me if I've been overcomplicating things - I've been kinda afar from C++ lately (working on C# recently) thus might have mistaken the syntax an stuff, but logic should be the same anyway.
First the apologies, i'm not sure if my question title even accuratly explains what I'm asking - I've had a look through google, but i'm not sure which terms I need in my search query, so the answer may be out there (or even on StackOverflow) already.
I have a templated class, which basically looks like the following - it uses the Singleton pattern, hence everything is static, I'm not looking for comments on why I'm storing the keys in a set and using strings etc, unless it actually provides a solution. There's a bit more to the class, but that isn't relevant to the question.
template<typename T>
class MyClass
{
private:
//Constructor and other bits and peices you don't need to know about
static std::set<std::string> StoredKeys;
public:
static bool GetValue(T &Value, std::string &Key)
{
//implementation
}
static SetValue(const T Value, std::string &Key)
{
//implementation
StoredKeys.Insert(Key);
}
static KeyList GetKeys()
{
return KeyList(StoredKeys);
}
};
Later on in some other part of the application I want to get all the Keys for all of the values - regardless of type.
Whilst I am fairly confident that at the moment only 3 or 4 types are being used with the class so I could write something like:
KeyList Keys = MyClass<bool>::GetKeys();
Keys += MyClass<double>::GetKeys();
Keys += MyClass<char>::GetKeys();
This will need to be updated each time a new type is used. It also has the downside of instantiating the class if it's not used anywhere.
I think (again I could be wrong) that metaprogramming is the answer here, some sort of macro maybe?
We're using boost, so I'm guessing the MPL library could be useful here?
This aspect of STL is a bit new to me, so I'm happy to read up and learn as much as I need, just as soon as I know exactly what it is I need to learn to engineer a solution.
Move StoredKeys into a non-template base class class MyClassBase, or add an AllStoredKeys static member to a non-template base class.
Alternatively, create a static init method called from SetValue that adds a pointer to StoredKeys to a static list.
There's no magic. If you need to enumerate all the types used to instantiate MyClass in your program, then you have to enumerate them explicitly, somewhere. somehow. And you have to manually update the list whenever it changes.
With template metaprogramming, the number of places you need to update manually can be reduced down to one, but you do need that one place.
Fortunately, in this particular problem you don't need to enumerate all the types. You just need to store all keys in one set, as opposed to splitting them between several sets. You may create a common non-template base to MyClass and add static std::set<std::string> StoredKeys there (or perhaps make it a multiset if there's a possibility of identical keys in different type-specific sets).
The first answere: Its not possible!
Template classes dont actually have a "generics" in common (like in java) but a separate classes which dont have anything to do with eachother.
The second answere: Theres a workaround. One can define a base class MyClassBase which defines properties shared by all templated subclasses. The problem is that you have a singleton pattern here which might makes the situation a bit more compilcated. I think a solution might look like this:
class MyClassBase {
static std::vector<MyClassBase*> childs;
static KeyList getAllKeys(){
//iterate over childs here and call ->GetKeys
}
virtual KeyList GetKeys() = 0;
template<typename T>
static T* instance() {
T* instance = MyClass<T>::instance();
if(std::find(childs.begin(), childs.end(), instance) != childs.end()){
childs.push_back(instance);
}
return instance;
}
};
Please forgive me any syntactic errors; I just typed that in the Stackoverflow editor, but i think it should make my point clear.
Edit:
I just saw that I named the singleton method of the subclasses also instance(). This will probably not work. Give it some other name like privateInstance() or so. Then you must change T* instance = MyClass<T>::instance(); to T* instance = MyClass<T>::privateInstance();
I'm implementing several classes using the pimpl idiom and am coming across some design issues.
Firstly, I've always seen pimpl done like this
class Object
{
public:
Visible();
~Visible();
.. etc ..
private:
class ObjectImpl *_pimpl;
};
I have several classes which use this approach and my problem is that several of these classes need access to each others implementation details but the _pimpl pointer is delcared private.
Can anyone see the downside of declaring the _pimpl public. Obviously, if it's public then someone may accidentally (or deliberately) reassign it. (I'm ignoring the fact that "private" could be #defined as "public" and grant access anyway. If you do this then you deserve what you get).
I appreciate that my design may be flawed and would welcome any comments along those lines also.
I'm really loathe to use friends and am not sure they'll even help as you can't forward declare the Object::ObjectImpl without fully defining Object.
i.e.
...
private:
class ObjectImpl *_pimpl;
friend class OtherObject::OtherObjectImpl; // this needs a fully qualified OtherObject
};
Thx
Mark.
* UPDATE - More detail **
I have two classes, one called Command, the other called Results. I have methods on Command which return a vector of Results.
Both Command and Results use the pimpl idiom. I want the interface to Results to be as small as possible.
class Command
{
public:
void getResults( std::vector< Results > & results );
void prepareResults( std::vector< Results > & results );
private:
class CommandImpl *_pimpl;
};
class Results
{
public:
class ResultsImpl;
Results( ResultsImpl * pimpl ) :
_pimpl( impl )
{
}
private
ResultsImpl *_pimpl;
};
Now in Command::getResults(). I inject the ResultsImpl into the Results. in Command::prepareResults() I need access to the ResultsImpl.
M.
I doubt there is a good reason to make the implementation public: you can always expose the implementation's functionality using public methods:
class Object
{
public:
Object();
~Object();
int GetImplementationDetail();
private:
std::unique_ptr< ObjectImpl > _pimpl;
};
int Object::GetImplementationDetail()
{
return pimpl->GetImplementationDetail();
}
Apart from that a class should be responsible for one thing, one thing only, and should have the bare minimum of dependencies to other classes; if you think other classes should be able to access your Object's pimpl then your design is likely flawed.
edit following the author's update: although your example is still rather vague (or at least I cannot tell the full intent of it), you seem to be misinterpreting the idiom and now try to apply it to a case where it is not usefull. As others pointed out, the 'P' stands for private. Your results class doesn't have much private implementation since all of it is public. So either try to use what I mention above and do not 'inject' anything, or just get rid of the pimpl all together and use just the Result class. If your Result's class interface should be so small that it's nothing but a pointer to another class it doesn't seem to be of much use in this case.
Why exactly do your classes depend on details of each other? You may re-think your design. Classes should depend on abstractions.
If you really deem your design proper, nothing stops you from providing a "source-file-private" header, like:
include/
foo.h
src/
foo.impl.h
foo.c
bar.c
and then #include foo.impl.h in both foo.c and bar.c
foo.c:
#include "foo.impl.h"
...
bar.c:
#include "foo.impl.h"
...
But again: Generally,
Dependency Inversion Principle:
A. High Level Modules should not depend upon low level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.
Also make very sure to check out SOLID and GRASP, especially the point about loose coupling.
It is unnecessary to qualify the friend thusly.
If you just use friend class OtherObject, then the OtherObject class may access the necessary internals.
Personally my Pimpl are just a struct (bundle of data) and I leave the methods to operate on it in the original class.
Making the the data member _pimple public won't buy you anything as long as those other classes do not see the definition of its type ObjectImpl - which is the very thing Pimple set out to prevent.
What you can do instead is to add a private interface to your Object class which will allow befriended classes to do whatever they need to do with an Object.
Of course, the common disclaimers about friend being a tool that should be used as rarely as possible all apply.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should you use 'friend' in C++?
I see a lot of people recommending a function/class to be made a friend of another class here in SO though there are other alternatives. Shouldn't friend be sparingly used in C++? I feel other options must be considered before deciding on using the friend feature. Opinions/suggestions are welcome.
Some say friend is a violation of encapsulation. In my opinion, it is the exact contrary. Without friend, we would end up with either:
huge monolithic classes, that does plenty of things they were not meant to, just to avoid letting outer classes access their internals
badly encapsulated classes: to separate concerns and write classes with one and only one responsability, we would need to provide public access to internal data needed by the related set of classes.
friend is a good way to overcome this issue, since it lets you free to separate responsabilities in several classes, while at the same time letting you restrict access to implementation details to the few functions or types which need them.
I agree. The friend keyword should be used sparingly.
It may be useful if you have a set of classes that interact together when you want to expose a clean api from those classes to users, but when the classes can interact with each other using a richer interface.
Eg:
class Folder
{
public:
int GetFileCount();
private:
void IncrementFileCount(); // users of this class have no right to use this
friend class File;
};
class File
{
public:
File(string name, Folder& containingFolder)
{
containingFolder.IncrementFileCount(); // except for indirectly when they create a file
}
};
Without specific examples this is hard to decide. While friend isn't strictly necessary it does have its uses. If, as you claim, there are better alternatives then obviously use them, by simple definition of the word “better”. Or maybe the decision which solution is better isn't that clean-cut after all.
Personally, I prefer to avoid it when possible but I prefer to use it over method duplication: for example, I do not like to write a print method just to avoid making operator << a friend because I don't see the benefit of the duplicate method.
For all those who thinks friend violates the encapsulation, here is what Bjarne Stroustup has to say .
But I personally don't use friend unless it is inevitable. Scenarios like implementation of Iterator patterns there is no other choice.
Friend is friend if used properly otherwise he is enemy!
Friend functions are advantageous in cases where you would want to call a 3rd party library function which needs access to members of your class, consider for example:
class A {
private:
int x,y;
double result;
public:
friend void *power(void *x);
}
You can now call the pow function found in math.h using this friend function.Your power function can now be defined as:
void *power(void *X)
{
A *a;
a = static_cast< A *> (X);
a->result = pow(a->x,a->y);
return NULL;
}
Although there are easier ways of calling the pow function.This example is only meant to illustrate the importance of friend function in calling library functions.
Hope it is useful.
While designing an interface for a class I normally get caught in two minds whether should I provide member functions which can be calculated / derived by using combinations of other member functions. For example:
class DocContainer
{
public:
Doc* getDoc(int index) const;
bool isDocSelected(Doc*) const;
int getDocCount() const;
//Should this method be here???
//This method returns the selected documents in the contrainer (in selectedDocs_out)
void getSelectedDocs(std::vector<Doc*>& selectedDocs_out) const;
};
Should I provide this as a class member function or probably a namespace where I can define this method? Which one is preferred?
In general, you should probably prefer free functions. Think about it from an OOP perspective.
If the function does not need access to any private members, then why should it be given access to them? That's not good for encapsulation. It means more code that may potentially fail when the internals of the class is modified.
It also limits the possible amount of code reuse.
If you wrote the function as something like this:
template <typename T>
bool getSelectedDocs(T& container, std::vector<Doc*>&);
Then the same implementation of getSelectedDocs will work for any class that exposes the required functions, not just your DocContainer.
Of course, if you don't like templates, an interface could be used, and then it'd still work for any class that implemented this interface.
On the other hand, if it is a member function, then it'll only work for this particular class (and possibly derived classes).
The C++ standard library follows the same approach. Consider std::find, for example, which is made a free function for this precise reason. It doesn't need to know the internals of the class it's searching in. It just needs some implementation that fulfills its requirements. Which means that the same find() implementation can work on any container, in the standard library or elsewhere.
Scott Meyers argues for the same thing.
If you don't like it cluttering up your main namespace, you can of course put it into a separate namespace with functionality for this particular class.
I think its fine to have getSelectedDocs as a member function. It's a perfectly reasonable operation for a DocContainer, so makes sense as a member. Member functions should be there to make the class useful. They don't need to satisfy some sort of minimality requirement.
One disadvantage to moving it outside the class is that people will have to look in two places when the try to figure out how to use a DocContainer: they need to look in the class and also in the utility namespace.
The STL has basically aimed for small interfaces, so in your case, if and only if getSelectedDocs can be implemented more efficiently than a combination of isDocSelected and getDoc it would be implemented as a member function.
This technique may not be applicable anywhere but it's a good rule of thumbs to prevent clutter in interfaces.
I agree with the answers from Konrad and jalf. Unless there is a significant benefit from having "getSelectedDocs" then it clutters the interface of DocContainer.
Adding this member triggers my smelly code sensor. DocContainer is obviously a container so why not use iterators to scan over individual documents?
class DocContainer
{
public:
iterator begin ();
iterator end ();
// ...
bool isDocSelected (Doc *) const;
};
Then, use a functor that creates the vector of documents as it needs to:
typedef std::vector <Doc*> DocVector;
class IsDocSelected {
public:
IsDocSelected (DocContainer const & docs, DocVector & results)
: docs (docs)
, results (results)
{}
void operator()(Doc & doc) const
{
if (docs.isDocSelected (&doc))
{
results.push_back (&doc);
}
}
private:
DocContainer const & docs;
DocVector & results;
};
void foo (DocContainer & docs)
{
DocVector results;
std :: for_each (docs.begin ()
, docs.end ()
, IsDocSelected (docs, results));
}
This is a bit more verbose (at least until we have lambdas), but an advantage to this kind of approach is that the specific type of filtering is not coupled with the DocContainer class. In the future, if you need a new list of documents that are "NotSelected" there is no need to change the interface to DocContainer, you just write a new "IsDocNotSelected" class.
The answer is proabably "it depends"...
If the class is part of a public interface to a library that will be used by many different callers then there's a good argument for providing a multitude of functionality to make it easy to use, including some duplication and/or crossover. However, if the class is only being used by a single upstream caller then it probably doesn't make sense to provide multiple ways to achieve the same thing. Remember that all the code in the interface has to be tested and documented, so there is always a cost to adding that one last bit of functionality.
I think this is perfectly valid if the method:
fits in the class responsibilities
is not too specific to a small part of the class clients (like at least 20%)
This is especially true if the method contains complex logic/computation that would be more expensive to maintain in many places than only in the class.