I have a template class that I have made called hash. My template class hash takes three non-type parameters. The definition of the hash class is below:
template <typename array_type, typename ptr_to_hash, typename hash_type>
class hash
{
public:
//default constructor
hash();
/* Overloaded Constructors */
// instantiates a hash object and the pointer to the hash_function
hash(const int&, std::ifstream&, const char*, ptr_to_hash*);
/* Methods for Hash Class */
void insert_to_hash();
// some other stuff
};
As you can see I want my non-type parameter ptr_to_hash to be a pointer to my function void insert_to_hash. The implementation of the above overloaded contructor looks like:
template <typename array_type, typename ptr_to_hash, typename hash_type>
hash<array_type, ptr_to_hash, hash_type>::hash(const int& dim, std::ifstream& in, const char* file, ptr_to_hash* hash_ptr)
{
// do some stuff to allocate from file
// point function pointer to correct function
hash_ptr = &this->insert_to_hash();
}
Now in main I am attempting to create a pointer to my hash function. So I first create a void function pointer and then pass that to my overloaded constructor:
int main()
{
// create void function pointer
void (*foo)();
//create hash obj. from data read in from argv[1]
hash< member<int>, void(*), member<int> > awesome( count_lines(in,file), in, file, foo);
}
In the above member<int> is a template struct and count_lines() just returns an integer value for the amount lines in the file. When I attempt to do this I get the error
no matching function for call to ‘hash<member<int>, void*, member<int> >::hash(int, std::ifstream&, const char*&, void (*&)())
When I look at the error above I seem to be passing my foo function pointer object as *& which of course does not match any function calls in my class.
That is the crux of my problem. I am unsure of how to pass a function pointer that points to my void insert_to_hash() in my hash class when using templates. I am clearly doing it wrong.
The type of
fooas a reference isvoid(&)(), and as a pointer it isvoid(*)(). I would omit the explicit pointer from the template signature and let it be part of the argument:You could also declare
run(FRef * f) { f(); }and sayrun<void(&)()>(foo), but I wouldn’t bother. There’s no way to not have the pointer in a function pointer, so you might as well absorb it into the argument type itself.