Reputation: 16255
Hi I have the following classes:
template<class T>
class RandomTree<T> {
private:
RandomTreeNode root;
typedef double (*funcion_ptr) (T, T);
public:
RandomTree(std::vector<function_ptr> functions){...}
};
template<class T>
class RandomTreeNode<T> {
private:
typedef double (*funcion_ptr) (T, T);
function_ptr function;
public:
RandomTreeNode(function_ptr function){...}
};
The tree is given a vector of function pointers and each node is created and has one particular function. Is there a way for me to not have to define the typedef double (*function_ptr) (T,T)
in both classes?
Upvotes: 1
Views: 170
Reputation: 409166
As you are declaring a free-standing function pointer type, as opposed to a member-function pointer, you could of course put the typedef in a separate templated class in global scope or in a namespace, so it can be accessed by both classes.
Like this:
template<class T>
struct RandomTreeFunction
{
typedef double (*function_ptr)(T, T);
};
template<class T>
class RandomTree<T> {
private:
typedef typename RandomTreeFunction<T>::function_ptr function_ptr;
...
};
I also recommend you to look into using std::function
instead.
Upvotes: 3
Reputation: 70516
If you have acccess to a compiler (e.g. gcc >= 4.7, clang >= 3.0) that supports template aliases, you can do something like
#include <vector>
template<class T>
using function_ptr = double (*)(T,T);
template<class T>
class RandomTreeNode {
private:
function_ptr<T> function;
public:
RandomTreeNode(function_ptr<T> function){/*...*/}
};
template<class T>
class RandomTree {
private:
RandomTreeNode<T> root;
public:
RandomTree(std::vector<function_ptr<T>> functions){/*...*/}
};
Otherwise, the solution by Joachim Pileborg is adequate.
Upvotes: 0
Reputation: 15289
If you make it public in RandomTreeNode<T>
you can say then:
template<class T>
class RandomTree<T> {
typedef RandomTreeNode<T>::funcion_ptr function_ptr;
};
or use RandomTreeNode<T>::funcion_ptr
directly, which would be quite tedious.
Upvotes: 0