Define std::hash<std::function> - c++

I need to create a templated class that can hold pointers to elements of type T and then performs functions on them. The functions will come from different places, so I need a container to store them, so I can call them later. I decided to use an std::unordered_set, because it offers speed and restricts duplication due to it being implemented as a hash table. I have a whole class written, but it doesn't compile due to there not being a hash function defined for my std::function that takes a pointer of type T and returns void. It's easy enough to specify it with struct hash<std::function<void(MyCustomType*)>> (and overloading the () operator, too) for each type I use, but how do I actually hash the function?
Here is a watered-down excerpt from my class with the relevant members and methods:
template <typename T>
class Master {
private:
std::unordered_set<std::function<void(T*)>> functions;
protected:
registerFunction(std::function<void(T*)> function) {
this->functions.insert(function);
}
unregisterFunction(std::function<void(T*)> function) {
this->functions.erase(function);
}
};
I'm not completely bound to using an std::unordered_set, but it seems to offer everything that I'd need to get this piece (and the rest of my code) working well.
Am I thinking about this the wrong way? Is it completely impossible to hash a std::function?

A set is mostly something you will check that data is in it.
So I do not see the point of using one here... You'll have your functions and you'll store them in the set, and after that, what ? You just iterate on them ?
For your question, a element of a set should have a way to generate a hash and an operator==(). The second is not provided for std::function and thus you wouldn't be able to check that your function is really in the set.
So even if you find a way to generate an hash from the function, you would be stuck... And I do not see how to meet the hash requirement.
Why not simply use a std::vector ?

Related

Basic interface for sorting algorithms classes

I need to program some sorting algorithms, for this I want to have base interface with virtual function Sort(). The problem is that I don't really know which type of elements client will use. I only need comparison operator to be available for this type. So, it could be template, but i can't use template and virtual simultaneously. I need advice on architecture of this code.
Also, it would be good to have ability to pass either allocator or memory in case of not inplace sorts. Where I need to insert this part. Maybe as an optional parameter.
May be I don't need classes at all and another kind of program structure suits better. Thanks.
EDIT:
How to use:
obj.SetStrategy(specificAlgortihm);
obj.Execute(array);
...
template <class T>
void Obj::Execute(array)
{
m_Algorithm->Sort(array);
}

Can I access a struct passed into a template generically?

As per the title, this is what I am looking to do. Basically I am looking to load in structures from files, but support every kind of structure, so I am attempting to do it in a template. This is my first time using templates really so excuse my ignorance!
I want to be able to do something like:
template<class T> T ConfigLoader::LoadStructFromFile(T a)
{
int noOfThingsInStruct;
noOfThingsInStruct = a[1];
return a;
}
Is this at all possible?
My function does sorting of the string loaded in from files etc but thought I would leave that part out.
I want to be able to get this value to use it to loop and give the struct the correct number of values it is looking for.
So you want to dynamically figure out what members and methods are in a struct? Similar to, say, what you can do in Javascript in runtime, but in compile time? No, you can't. However, you can make a template policy and base this function on that.
Simple answer: impossible.
Long answer: still no.
Detour:
you can use something based on type traits. Create a template class numberOfElements<typename T> and overload it for every struct you need with a value you expect. Then, use it in your LoadStructFromFile, since you know T.
You can also use SFINAE to test for some function that'll return the number of elements in a struct. If a given class/struct implements it, just use it to get the number of members. If not - assume there's only 1 member (or whatever you wish).

Where to implement the hash function?

I am using an object as a key in an unordered_map, so I need to define a hash function. My question is, where should the hash function be implemented. Should I put it with the class implementation or should I implement it close to where I need it.
UPDATE:
If it makes a difference, all of this is based in a framework
If you anticipate you'll need to reuse it in many unordered_maps, put it somewhere visible, like in the class.
If you just need it for a one-off unordered_map, put it close to where you use it. You can even use a lambda.
I'd put it with the class definition, at least if you're using == as
the equality function in the unordered_map. The implementation of the
hash function depends on the implementation of the equality comparison,
and there is a definite advantage in keeping both together, to reduce
the probability of someone not changing the hash function if they
change ==.
If you're also defining a special equality function for the map, then
the two functions should be defined together, probably close to where
they will be used to instantiate the map.
In my opinion if the hash function is basic as below it should be method of the class and also should be inline.
int hashFunction(long x){
return (int) (x % N);
}
If it is a little more complex hash function it should be a method of this class.Because you will need a "N" which will be spesific to that class .

A collection of custom structures (a wrapper) with a single member (also a custom structure), to a collection of the single members

The problem is specific but the solution open ended. I'm a lone coder looking to bat some ideas around with some fellow programmers.
I have a wrapper for a maths library. The wrapper provides the system with a consistent interface, while allowing me to switch in/out math libraries for different platforms. The wrapper contains a single member, so say for my Matrix4x4 wrapper class there is an api_matrix_4x4 structure as the only member to the wrapper.
My current target platform has a nifty little optimised library, with a few of those nifty functions requiring a C-style array of the wrapper's embedded member, while my wrapper functions for those math API functions don't want to expose that member type to the rest of the system. So we have a collection of wrappers (reference/pointer to) going into the function, & the members of the wappers being needed in a collection inside the function, so they can be passed to the math API.
I'm predominantly using C++, including C++11 features, & can also go C-style. Ideally I want a no-exception solution, & to avoid as many, if not all dynamic allocations. My wrapper functions can use standard library arrays or vectors, or C-style pointers to arrays as parameters, & whatever is necessary internally, just no dynamic casting (Run-Time Type Information).
1) Can I cast a custom struct/class containing a single custom struct, to the custom struct? If so, what about if it was a standard library collection of them. I'm thinking about type slicing here.
2) Would you perhaps use a template to mask the type passed to the function, although the implementation can only act on a single type (based on the math API used), or is such usage of templates considered bad?
3) Can you think of a nifty solution, perhaps involving swaps/move semantics/emplacement? If so, please help by telling me about it.
4) Or am I resigned to the obvious, iterate through one collection, taking the member out into another, then using that for the API function?
Example of what I am doing by the wrapper struct & wrapper function signature, & example of what I am trying to avoid doing is given by the function implementation:
struct Vector3dWrapper
{
API_Specific_Vector_3d m_api_vector_3d;
inline void operation_needing_vector_3d_wrappers(std::vector<Vector3d>& vectors)
{
// Now need a collection of API_Specific_Vector_3ds
try
{
std::Vector<API_Specific_Vector_3d> api_vectors;
api_vectors.reserve(vectors.size());
for( auto vectors_itr = vectors.begin(); vectors_itr != vectors.end(); ++vectors)
{
// fill each Vector3d.m_api_vector_3d into api_vectors
}
}
catch(std::bad_alloc &e)
{
// handle... though in reality, try/catch is done elsewhere in the system.
}
// Signature is API_Multiply_Vectors_With_Matrix_And_Project(API_Specific_Vector_3d* vectors, size_t vector_count)
API_Multiply_Vectors_With_Matrix_And_Project(&api_vectors, api_vectors.size());
}
};
You can cast a standard-layout struct (such as a struct compatible with C) to its first member, but what's the point? Just access the first member and apply &.
Templates usually allow uniform parameterization over a set of types. You can write a template that's only instantiated once, but again that seems pointless. What you really want is a different interface library for each platform. Perhaps templates could help define common code shared between them. Or you could do the same in plain C by setting typedefs before #include.
Solution to what? The default copy and move semantics should work for flat, C-style structs containing numbers. As for deep copies, if the underlying libraries have pointer-based structures, you need to be careful and implement all the semantics you'll need. Safe… simple… default… "nifty" sounds dirty.
Not sure I understand what you're doing with collections. You mean that every function requires its parameters to be first inserted into a generic container object? Constructing containers sounds expensive. Your functions should parallel the functions in the underlying libraries as well as possible.

Member functions for derived information in a class

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.