Reputation: 14659
In C, I can do this.
typdef void(TRAVERSAL_CALLBACK*)(int a);
That would then allow me to pass function pointers to other functions as arguments, with that function having 1 argument of type int.
I've been working with templates, and currently, passing the function pointer to the method works like this:
void my_function(void(TRAVERSAL_CALLBACK*)(T &data));
Now, is it possible if I define a new type with argument of type T. I have tried but it has failed to compile.
typedef void(TRAVERSAL_CALLBACK*)(T &data);
I'm using C++11. Is this something that I have to accept as not possible, or is there an idomatic way to do this in C++11 that I am not aware of?
Upvotes: 1
Views: 78
Reputation: 7881
In C++11, there is template type aliasing using the using
statement, example shown below:
#include <iostream>
using namespace std;
template <typename T>
T foo() {return 10;}
template <typename T>
using fptr = T (foo*)(void);
int main()
{
fptr<int> x1 = foo<int>;
fptr<double> x2 = foo<double>;
cout << "Hello World" << endl;
return 0;
}
However, in your case you most likely don't need to go that far. If you define the type within the scope of the template, it should work fine:
template <typename T>
struct bar
{
typedef T (*qiz)(void);
void baz(qiz q)
{
std::cout << q << std::endl;
}
};
Upvotes: 3
Reputation: 126927
Yes, in C++11 it's possible, thanks to the "new" using
:
template<typename T>
using TRAVERSAL_CALLBACK = void(*)(T &data);
Notice however that in C++ you'd probably just make the whole type of the callback a template, to allow the usage of other types of callable objects (functors, lambdas, ...).
Upvotes: 6