I'm developing a templated binary search tree in C++ for a data structures class right now. Everything has been going well until now. This issue deals with some nitty gritty C++ stuff that I'm not to familiar with, and I need help.
I've previously defined functions that traverse the tree and visit each node in different orders. The one in question here is defined as follows.
TreeNode.h
public:
static void PostOrderVisit(TreeNode<T>* node, void visit(const T& v));
TreeNode.cpp
template <class T> void TreeNode<T>::PostOrderVisit(TreeNode* node, void visit(const T& v)) {
if (node->leftChild != NULL)
PostOrderVisit(node->leftChild, visit);
if (node->rightChild != NULL)
PostOrderVisit(node->rightChild, visit);
visit(node->value);
}
This works fine in a test program that makes nodes and statically calls PostOrderVisit.
In a friend class (BinSTree.h/cpp), I am implementing a method that deletes every node in the tree, so I thought it would be a good idea to use this visitor and call my Delete() function on each node (the Delete() function also works fine in test programs for the BinSTree).
This function is defined as follows.
template <class T> void BinSTree<T>::ClearTree() {
TreeNode<T>::PostOrderVisit(this->root(), &BinSTree<T>::Delete);
}
And here lies the problem. g++ says...
BinSTree.cpp:156: error: no matching function for call to ‘TreeNode<int>::PostOrderVisit(TreeNode<int>*, void (BinSTree<int>::*)(const int&))’
TreeNode.cpp:56: note: candidates are: static void TreeNode<T>::PostOrderVisit(TreeNode<T>*, void (*)(const T&)) [with T = int]
In this case, I thought that void (BinSTree<T>::*)(const T&) would be an instance of void (*)(const T&), but it is not. The only way I can get the call to be recognized by the function definition is by casting the function pointer like this:
TreeNode<T>::PostOrderVisit(this->root(), (void (*)(const T& v)) &BinSTree<T>::Delete);
This recognizes the function and calls it appropriately, however (this took some significant research...), C++ member functions have an implicit parameter that allows the 'this' keyword to be accessed from within. Casting a member function pointer to a plain function pointer drops the 'this' reference altogether, causing my Delete() method to seg fault (it uses 'this' quite a bit).
This has been a HELL of a hassle, and I have spent quite a bit of time on such a small bit of this project. Can anyone show me a way to either A: make the function be recognized without the casting, or B: how to maintain the 'this' reference throughout the cast. The ClearTree() and Delete() methods are both within the same class.
Thanks in advance.
First of all, PostOrderVisit should take the function argument as a pointer, i.e. PostOrderVisit(TreeNode<T>* node, void (*visit)(const T& v)).
However, that wont solve your problem because you are passing it a non-static member function. Either the function you pass to it has to be static in the class, or you can use something like std::function instead of a function pointer argument, i.e. PostOrderVisit(TreeNode<T>* node, std::function<void(const T&)> visit).
Edit
In that case I think you have two ways you can do this: One is to change your design to fit the parameter, that means you can not use member methods as a parameter. The second is to change the code to fit your design, and explain to the teacher that you had to change the interface due to its limitations, and explain those limitations.
The problem with using a normal function pointer as argument is that member functions have an implicit and hidden argument, this, for the instance of the class. Normal functions do not have this hidden parameter, and so the compiler prohibits you from using a member function. The solution is to either use normal functions, which is not very C++-ish, another is to use static member functions (as they don't have a this pointer), or use something like std::function.
As for how to use std::function, you use it in the declaration and definition of PostOrderVisit like I've shown. When you call it you do something like this:
template <class T> void BinSTree<T>::ClearTree() {
TreeNode<T>::PostOrderVisit(this->root(), std::mem_fn(&BinSTree<T>::Delete));
}
Non-static methods take an implicit parameter for "this". E.g. for a method C::f(int i), you can think of it like f(C* this, int i). Any casting that you do and screws up this signature you can expect badness to happen. You have already experienced crashes but more sinister artifacts could make the program misbehave or crash at other seemingly random places.
You can use pointer to member function like this:
in .h
template <class C>
static void PostOrderVisit(C* node, void (C::* visit)(const T& v));
in .cpp (actually if it is a template it has all to be in h, otherwise link error)
template <class T>
template <class C>
void TreeNode<T>::PostOrderVisit(C* node, void (C::* visit)(const T& v))
{
// ...
T value;
(node->*visit)(value);
// ...
}
You either pass pointer to your derived class (C as in here) or pointer to base class (TreeNode as in original). At some point you may need to cast.
You can also leave original function for when you pass a normal function as visitor. Function overload would take care.
A more generic way can be to use std::function. Although it may have some minor performance hit it would be most generic.
e.g. (have not compiled may have some minor syntax errors):
static void PostOrderVisit(TreeNode<T>* node, std::function<void (const T& v)> visit);
Inside PostOrderVisit you just do visit(value), e.g. call like normal function.
When you call PostOrderVisit you can use all the power of std::bind or boost::bind to carry as much extra info as you wish. E.g.
PostOrderVisit(this->root(), std::bind(&BinSTree::Delete, this));
Related
So I got myself onto shaky ground by insisting on making a C++ class immitate a regular function. The class overloads the function operator, making it a functor, of course. This all works fine, until you want to pass the function pointer of this functor.
Naturally, I want to let the compiler know that we know what we're doing (lol), by doing a reinterpret_cast of this pointer. However, how do I get the address of this particular member function, since it is an overloaded operator. How does one get the address of that?
UPDATE: You asked for an example. Here is a minimal one.
So I have an interface, which I cannot change. It looks like this;
typedef void (*some_callback_t)(SomeType);'
void someFunc(some_callback_t);
Now, this is quite straight-forward; the API is setting some callback function pointer. So, the idea was to implement the callback as a functor class, by overloading the operator(), like so, as usual.
class Bah {
void operator()(SomeType);
};
Here comes the question; seeing as I cannot change the API used (the function that expects a function pointer of a certain signature), how can I then get the address of the member function and pass that?
I suspect it goes something like;
someFunc(reinterpet_cast<some_callback_t>( ? ? ? )); to make sure that the compiler won't barf at me.
Supposing that you have to use a function pointer, and that your functor has no state, you can use a lambda as glue:
void takesFunctionPointer(void (*)());
struct MyFunctor {
void operator()();
};
// ...
takesFunctionPointer([] { return MyFunctor{}(); });
How does one get the address of that?
In the same way as any other member function. The name of the function is class_name::operator(). An example:
struct class_name {
void operator()(){}
};
void (class_name::*member_function_pointer)() = &class_name::operator();
class_name instance;
(instance.*member_function_pointer)(); // in a block scope
Naturally, I want to let the compiler know that we know what we're doing (lol), by doing a reinterpret_cast of this pointer.
That's usually not what one would want to do.
I don't understand why the following code compile and works:
template<typename Predicate>
void foo(Predicate p) {
}
bool g(int n) {
}
void user(int n) {
foo(g);
}
foo is supposed to get a function object that will run on a data structure but I made the method simpler, because what I don't understand is how can this works? A method isn't an object. The normal way to do it is to create a new class, override operator() and then send an instance of that class.
Well, in this case the Predicate parameter is substituted by a function pointer of type bool (*func) (int). Nothing wrong with that...
The Predicate template argument can be almost any type. So you can use it for function pointers and classes as well as the basic types.
If you use the function argument p as a function, then it can be anything that is callable, like a function pointer, an object whose class have an operator() member function, a pointer to a static member function, a std::bind object, a std::function object or a lambda expression.
It can't be a pointer to a member function though, because to call a pointer to a member function you need an instance to call it on. For this use std::bind.
I'm having some trouble creating a static wrapper function using template parameters. I don't want to pass the function directly to the wrapper function, because it needs a specific signature int (lua_State *) so that it can be passed into the following function:
lua_pushcfunction(L, function);
(That's right, I'm going for an auto-generated lua wrapper.)
My first thought is to create a template function with a function pointer as a non-type template argument.
template <void(* f)(void)>
int luaCaller(lua_State * _luaState)
{
f();
return 0;
}
So far, this is looking pretty good. This function has the proper signature, and calls a function I pass in via template argument.
&(luaCaller<myFunc>)
My problem arises when I try to wrap this in another function. Non-type template parameters must be externally linked, and thus the following fails:
void pushFunction(lua_State * _luaState, void(* _f)(void))
{
lua_pushcfunction(_luaState, &(luaCaller<_f>));
}
Which makes sense, because the address of the function needs to be known at compile time. You can't throw in just any pointer and expect the compiler to know which classes to create. Unfortunately, if I add a function pointer that is known at compile time it still fails. The value of the function pointer is being copied into _a, and therefore _a is still technically not known at compile time. Because of this, I would expect the following to work:
void pushFunction(lua_State * _luaState, void(* const _f)(void))
{
lua_pushcfunction(_luaState, &(luaCaller<_f>));
}
or maybe
void pushFunction(lua_State * _luaState, void(* & _f)(void))
{
lua_pushcfunction(_luaState, &(luaCaller<_f>));
}
In the first case, because the value isn't allowed to change, we know that if it is externally linked, it will still technically be externally linked. In the second case it's being passed in as a reference, which would mean it should have the same linkage, no? But neither of these attempts work. Why? Is it possible to circumvent this somehow? How can I cleanly auto generate a function that calls another function?
The const qualifier means you aren't allowed to change something, not that it's a compile-time constant. The initial value of _a is determined at runtime when the function is called, and for a * const &a, the value can even change at runtime by some external means such as another thread, if the object underlying the reference is not const.
To make the fully templated wrapper work, you need to give the compiler enough information to compile a function for each possible template argument, and provide logic to switch among those functions. The template system generates and organizes related functions, but it's not a dynamic dispatcher.
If you can add the function pointer to the lua_State object and eliminate the template parameter, that would be one solution.
Your solution would work if make the function pointer a template argument to doCaller, but that would defeat its purpose.
Rather than using a non-type function-template approach in order to bind the secondary function you want to call inside the wrapper-function, you could use a struct with a static luaCaller method. That should allow you to maintain the function signature you need for passing luaCaller to lua_pushcfunction.
So for instance, you could have a struct that looks something like the following:
template<void (*f) void>
struct wrapper
{
static int luaCaller(lua_State * _luaState)
{
f();
return 0;
}
};
template<typename Functor>
void doCaller(lua_State * _luaState, Functor wrapper)
{
Functor::luaCaller(_luaState);
}
then call it like:
doCaller(&luaState, wrapper<my_func>());
I am trying to make a vector hold void pointers to functions, which will later be called secuentially.
So, lets say that I have got three functions. int a(), void b();, bool c();
My vector is vector<void *> vec;
And my function that stores pointers to functions.
void registerFunction(void *func)
{
vec.push_back(func);
}
Now my problem is when trying to call all the functions stored, since they are all void pointers, I just cannot call the functions without knowing their type.
So my question is... is there any way to store types of symbols so I can relate them to their respective pointers and then typecast when calling a void pointer to a function?
Note: Functions won’t be always be of type, for example, void (*)(), I will want to add methods also, hence ie. void (someclass::)(). Is it asking for too much? Should it work?
You cannot convert a function pointer to void*. It is not allowed.
If all of the functions are callable with zero arguments and you don't care about the return type, you can use std::vector<std::function<void()>> (function can also be found in Boost and TR1 if your C++ Standard Library does not support it).
Though, if I recall correctly, return-type conversion is not allowed in the C++11 std::function implementation, in which case you may need something like the following:
template <typename T>
struct ignore_result_impl
{
ignore_result_impl(T fp) : fp_(fp) { }
void operator()() { fp_(); }
T fp_;
};
template <typename T>
ignore_result_impl<T> ignore_result(T fp)
{
return ignore_result_impl<T>(fp);
}
int g() { return 42; }
std::function<void()> f(ignore_result(g));
(In the Boost implementation I know you can use function<void()> directly, but I'm pretty sure that is no longer allowed in C++11. I could be wrong and I'd appreciate clarification in the comments, if someone does know.)
void* can't safely be used as a generic pointer-to-function type (though you might be able to get away with it).
But any function-to-pointer value can be converted to another pointer-to-function type and back again without loss of information. So you can use, for example, void (*)() (pointer to function returning void and taking no arguments) as a generic pointer-to-function type.
As for storing the type, I'm not sure that's possible. If there are only a limited number of possibilities, you can use an enumeration type and a switch statement.
But you'll probably be better off using a design based on inheritance.
As long as all the functions follow the same type signature, you can cast the void pointers back to that type.
A better solution is to typedef the function type:
typedef int(*fun_ptr)();
vector<fun_ptr> vec;
Then you will not need the cast.
Given a class with a member template function like this one:
template <typename t>
class complex
{
public:
complex(t r, t im);
template<typename u>
complex(const complex<u>&);
private:
//what would be the type of real and imaginary data members here.
}
I am confused about member template functions, please provide an example by which the need of member template functions becomes clear to me.
Also, tell me the use of member template functions in c++, what are the situations where we use member template functions?
It gives you the ability to do conversions:
complex<int> ci;
complex<float> cf(ci);
So, if you have two types T1 and T2 and you can assign a T1 to a T2, this will make it possible to assign a complex<T1> to a complex<T2>.
As for the question in your code (what would be the type of real and imaginary data members here):
template <typename t>
class complex
{
...
private:
t real_part;
t imaginary_part;
};
The most common valuable use for member template functions I come across in my day-to-day is to reduce code complexity by providing one templated function instead of many functions that do essentially the same thing.
For example, suppose you are working on a server that receives half a dozen related messages and saves the incoming data to half a dozen tables in a database. A straightforward implementation would be to implement 6 message handling functions (psudocode):
class MessageProcessor
{
void OnMessage(const char* msg);
void ProcessMessage100(Data100* data);
void ProcessMessage101(Data101* data);
void ProcessMessage102(Data102* data);
void ProcessMessage103(Data103* data);
void ProcessMessage104(Data104* data);
void ProcessMessage105(Data105* data);
};
MessageProcessor::OnMessage(const char* msg)
{
unsigned int * msgType = ((unsigned int*)msg);
switch( *msgType )
{
case 100 :
ProcessMessage100((Data100*),sg);
break;
case 101 :
ProcessMessage101((Data101*),sg);
break;
::
}
}
MessageProcessor::ProcessMessage100(Data100* data)
{
Record100* record = GetRecord100(key);
record->SetValue(xyz);
}
MessageProcessor::ProcessMessage101(Data101* data)
{
Record101* record = GetRecord101(key);
record->SetValue(xyz);
}
: :
There is an opportunity here to generalize the ProcessMessage() functions, since they do essentially the same thing:
class MessageProcessor
{
OnMessage(const char* msg);
template<class Record, class Data> void Process(Data* data);
};
template<class Record, class Data>
void MessageProcessor::Process<Record,Data>(Data* data)
{
Record* record = GetRecord(key);
record->SetValue(xyz);
}
The GetRecord function can also be generalized, yielding a codebase with 2 functions where there used to be 12. This improves the code by virtue of it being simpler with fewer moving parts, simpler to understand and maintain.
The general purpose and functionality of member function templates is in no way different from that of ordinary (non-member) function templates. The only [irrelevant] difference is that member functions have access to the implicit this parameter.
You understand the general purpose of ordinary function templates, do you? Well, in that case you should understand the general purpose of member function templates, because it is exactly the same.
Using the example you provided, the member template function allows you to construct an instance of complex<T> from complex<U>.
As a concrete example of when this might be useful, suppose you had a complex<double> but wanted a complex<float>. Without the constructor the types are unrelated so the regular copy constructor wouldn't work.
Often you would like some member function of your class to operate on a range. By having templated member functions you make it possible to operate on ranges independent of the container that supplies the range without providing an free function.
The same goes for Functors. Often you'd write a functor that operates on some sipecial pair of iterators but soon realize that it is possible to have the Functor operate on any kind of range. So instead of supplying the template parameters through the encapsulating struct you can supply them through the member function operator() and make type deduction possible.
The first examples that come to mind:
In some container constructors (or assign methods) to take input iterators of unknown type.
std::complex to allow operating on different types than the one the std::complex was instantiated from.
In shared_ptr (whether std::tr1:: or boost::) so that you can keep different types of pointers into a shared object instance in the heap (for which the pointer types can be obtained).
In thread (whether std:: in c++0x or boost::) to receive a functor of unknown type that will be called by the thread instance.
In all cases the usage is the same: you have a function that operates on types that are unknown. As AndreyT perfectly states the same that with regular functions.