Lets say I have an array of functions :
name::Function _actions[10];
The name::Function is just a wrapper for std::function:
class Function{
public :
std::function<void(float dt)> Function;
void exec(float dt){
Function(dt);
}
};
And now I have a function to make it generic so it can bind any classes functions :
template<class T>
void bindFunction(int action,void (T::*function)(float) , T* classPtr)
{
_actions[action] = boost::bind(&function, this, boost::placeholders::_1);
}
And want to use it inside a class that inherits this method (the base class is generic but I think it shouldn´t be a problem)
DefaultMovableEntity()
{
bindFunction(1, &DefaultMovableEntity::func1, this);
}
void func1(float dt)
{
//Code
}
However I keep getting erros :
What is the main problem? I thought im doing everything right. Thanks.
Edit1
After removing the & from the function and replacing this got following error:
There are several problems with your code:
You can't assign your bind result to the array since your array member type is Function, not std::function.
You need to remove & as said before in comments.
Your member named Function is same as class name so compiler may think you are trying to call class constructor.
The following code should work:
class Function {
public:
std::function<void(float)> func;
void exec(float dt) {
func(dt);
}
};
and bindFunction code:
template<class T>
void bindFunction(int action, void (T::*function)(float), T* classPtr)
{
_actions[action].func = boost::bind(function, classPtr, boost::placeholders::_1);
}
However I would suggest slight improvement of Function class so that it doesn't expose its members directly:
class Function
{
private:
std::function<void(float)> func;
public:
Function() = default;
Function(std::function<void(float)> f) : func(f) { }
void exec(float dt) {
func(dt);
}
};
And corresponding change of your bindFunction:
template<class T>
void bindFunction(int action, void (T::*function)(float), T* classPtr)
{
_actions[action] = Function(boost::bind(function, classPtr, boost::placeholders::_1));
}
Related
I am just thinking about a way to check an object to be valid in a automated way.
I have a couple of hardware related objects (like class A), which can be deleted by external (physical) events.
To detect this I have used shared/weak pointer. But now I am struggling with the checking of the weak pointer. Since this is done in the same way for each member function for many objects, I am currently searching for a way to do this with less redundant code.
In addition I am writing a library and do not want the user to handle this (simply return the weak pointer to the user to handle it by himself is therefor no option)
My best guess is shown below. My problem is, I could not find a way to generate the member functions (func1, and many more ...) automatically within the template. Doing it by myself would result in lot of redundant code for every member function to be validated (and there are a lot)
Each member function of A (and many more other objects) shall be wrapped by a function doing the validation shown below. This is same for all member functions and done for many classes which can be used as type for the Validator.
Does anyone has an idea how to solve this? Maybe there are other (better) ways to solve this.
Many thanks for your help.
Some constraints:
Only C++11 possible,
No exceptions
class A {
public:
void func1() {}
//many more functions
};
template<typename T>
class Validator
{
//has to be done for all functions of A
void func1()
{
if (!wptr.expired())
{
wptr.lock()->func1();
}
else
errorHandling();
}
private:
std::weak_ptr<T> wptr;
void errorHandling() {}
};
I would protect the full user function call:
class A {
public:
void func1() {}
//many more functions
};
template <typename T>
class Validator
{
public:
#if 1 // template way, but no-expressive signature
template <typename F>
void do_job(F f)
#else // type-erasure way, expressive, but with some overhead
void do_job(std::function<void (T&)> f)
#endif
{
auto t = wptr.lock();
if (t) {
f(*t);
} else {
errorHandling();
}
}
private:
void errorHandling();
private:
std::weak_ptr<T> wptr;
};
So user might chain call:
Validator<A> val;
val.do_job([](A& a)
{
a.func1();
a.func2();
});
If the caller can live with clunky syntax you can use member function pointers:
#include <memory>
#include <iostream>
class A {
public:
void func1() {
std::cout << "hello func1\n";
}
};
template<typename T>
class Validator
{
public:
Validator(std::shared_ptr<T> p) : wptr(p) {}
template <typename MemFun>
void call(MemFun mf) {
if (!wptr.expired())
{
(wptr.lock().get()->*mf)();
}
else
errorHandling();
}
private:
std::weak_ptr<T> wptr;
void errorHandling() {}
};
int main() {
auto x = std::make_shared<A>();
Validator<A> v{x};
v.call(&A::func1);
}
I'm reading a lot of questions (and answers) about function pointers, functors and callbacks but I still have a confusion about which is the right tool for me.
Some of them cannot apply to my scenario because it seems my compiler avr-gcc v5.4.0 does not have C++ standard library (i.e. std::function is not available).
This is my base class:
class Debouncer
{
public:
typedef uint8_t (Debouncer::*debouncer_raw_t) (void);
Debouncer() {}
void setRawFunction(Debouncer::debouncer_raw_t callback) { _raw = callback; }
private:
debouncer_raw_t _raw;
void anotherFunction()
{
uint8_t value = _raw();
// do something
}
}
In my other classes I have:
class Inputs
{
public:
Inputs()
{
_deb.setRawFunction(myRaw);
}
private:
Debouncer _deb;
uint8_t myRaw()
{
return something;
}
}
Of course this won't compile because myRaw is not static.
Anyway, I'm going to try to avoid this because it would break the existing code.
If I'm not wrong, a lot of questions seem to ask the other way around.
Instead I just want to pass the pointer of my member function to my Debouncer class, so it can call _raw() when it needs to.
Here I found this advise to avoid std:: library:
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
void userCode(Fred& fred, FredMemFn p) // Use a typedef for pointer-to-member types
{
int ans = CALL_MEMBER_FN(fred,p)('x', 3.14);
// Would normally be: int ans = (fred.*p)('x', 3.14);
// ...
}
But it seems the other way around. Here the class Fred is my Debouncer.
I don't want to call the Debouncer member, but member of the caller class (i.e. Input::myRaw()).
Would you please help me to understand which is the right tool to achieve such a simple task?
Making a member function virtual is a relatively low-overhead way to have a single pointer (to an object) refer to both the object's data and the correct member function.
class InputsBase
{
// All classes that implement myRaw() should inherit from this class
public:
virtual uint8_t myRaw() = 0;
};
class Inputs : public InputsBase
{
public:
Inputs()
{
_deb.setRawFunction(this);
}
private:
Debouncer _deb;
virtual uint8_t myRaw()
{
return something;
}
}
Your Debouncer can then simply store a pointer to the object in question.
class Debouncer
{
public:
typedef InputsBase* debouncer_raw_t;
Debouncer() {}
void setRawFunction(debouncer_raw_t callback) { _raw = callback; }
private:
debouncer_raw_t _raw;
void anotherFunction()
{
uint8_t value = _raw->myRaw();
// do something
}
}
If you know (or require) each of the classes using Debouncer have a public myRaw() function (or better operator(), or actually anything else), the problem is simpler:
template <typename T>
class Debouncer
{
public:
Debouncer (T* t): _t(t) {}
void anotherFunction()
{
uint8_t value = _t->myRaw();
std::cout << static_cast<int>(value);
}
private:
T* _t;
};
class Inputs
{
public:
Inputs() : _deb(this)
{
// beware, if Debouncer uses its parameter in constructor (like call a method),
// you cannot use initializer list
}
uint8_t myRaw()
{
return 13;
}
void foo()
{
_deb.anotherFunction();
}
private:
Debouncer<Inputs> _deb;
};
int main()
{
Inputs i;
i.foo();
}
This would be preferred solution in C++. See for example standard library <algorithm> - any function taking a predicate or some other callable expects to call it with operator() rathen than having to deal with pointers-to-member-function.
If you don't know what function should be called and you really cannot impose any requirement on the classes, you need to store both a pointer (or reference) to the class and a pointer to the member function. Note that you cannot connect pointers to member functions of different classes, so we need templates once again:
template <typename T, typename Func>
class Debouncer
{
public:
Debouncer (T* t, Func f): _t(t), _f(f) {}
void anotherFunction()
{
uint8_t value = (_t->*_f)(); //I get it now why isocpp asks to use macro here, the syntax is horrible
std::cout << static_cast<int>(value);
}
private:
T* _t;
Func _f;
};
class Inputs
{
public:
Inputs() : _deb(this, &Inputs::myRaw)
{
// beware, if Debouncer uses its parameter in constructor (like call a method),
// you cannot use initializer list
}
uint8_t myRaw()
{
return 13;
}
void foo()
{
_deb.anotherFunction();
}
private:
Debouncer<Inputs, decltype(&Inputs::myRaw)> _deb; //decltype is C++11, you could also declare type like you did in your question
};
int main()
{
Inputs i;
i.foo();
}
is there a way to implicitly pass the this of the calling class to a template function being called?
i tried the following so far:
template<class P, class T>
void funcA(P& p, T const* t = this){ //<--does not work.
//...some code here...
}
class TypeX { }
class TypeA {
public:
void DoSomething(){
TypeX x;
funcA(x, this); //compiles fine
//funcA(x); //<---my goal: implicitly pass "this" by default.
}
}
void main(){
TypeA objX;
objX.DoSomething();
}
for the type-of-"this" problem, i had the following working so far:
template<class T, class P>
constexpr auto funcA(P& p) {
//...some code here that also uses type T...
}
class TypeA {
public:
void DoSomething(){
TypeX x;
funcA<TypeA>(x); //<---explicitly passing TypeA. (compiles)
//funcA(x); //<---my goal.
//funcA<>(x); //<---my goal(fair enough)
}
}
}
as you can see, i explicitly pass the TypeA to funcA. looks like redundant to me. though it's currently running fine in my project, i tried making it cleaner by making funcA<TypeA>(x) to funcA(x). but no success so far. i'm hoping it's still possible to do this so i asked here in SO.
In a comment, you said,
funcA must be a non-member of a class, specially the target class it will be called.
Given that, it's not possible to use this as the default value of an argument of the function.
I don't see any problem with the following:
template<class P, class T>
void funcA(P& p, T const* t){
//...some code here...
}
class TypeX { };
class TypeA {
public:
void DoSomething(){
TypeX x;
funcA(x, this); // Explicitly pass "this".
}
};
It is not onerous either.
I'm building an interpreter and trying to avoid some boilerplate I run into when implementing builtin-functions. I am able to to do this by using templates.
Take this base template for instance:
template<ast::builtin_type T>
class builtin_procedure abstract : public builtin_procedure_symbol
{
using arg_traits = builtin_type_traits<T>;
protected:
builtin_procedure(const symbol_identifier& identifier): builtin_procedure_symbol(identifier)
{
this->register_param(arg_traits::param_id(), T);
}
/**
* The actual implementation of the built-in function
*/
virtual void invoke_impl(typename arg_traits::builtin_type) = 0;
public:
void invoke(scope_context& procedure_scope) override
{
auto raw_arg = procedure_scope.memory->get(procedure_scope.symbols.get(arg_traits::param_id()));
this->invoke_impl(arg_traits::get_from_expression(raw_arg));
}
};
To implement a built-in function function that takes a string, I only need to do:
class builtin_procedure_writeln final : public builtin_procedure<ast::builtin_type::string>
{
protected:
void invoke_impl(arg_traits::builtin_type arg) override;
public:
builtin_procedure_writeln();
}; /* Implementation in cpp file */
Very convenient, I only need to implement the virtual invoke_impl method and that's it.
I'm trying to wrap my head around getting this implemented with a variable number of template arguments so I don't have to duplicate my template definition if I want to support 2, 3, or more arguments in my derived implementation like in the example below.
This would be the template above to support a second template parameter:
template<ast::builtin_type T1, ast::builtin_type T2>
class builtin_procedure abstract : public builtin_procedure_symbol
{
using arg1_traits = builtin_type_traits<T1>;
using arg2_traits = builtin_type_traits<T2>;
protected:
builtin_procedure(const symbol_identifier& identifier): builtin_procedure_symbol(identifier)
{
this->register_param(arg_traits::param_id(1), T1);
this->register_param(arg_traits::param_id(2), T2);
}
/**
* The actual implementation of the built-in function
*/
virtual void invoke_impl(typename arg1_traits::builtin_type, typename arg2_traits::builtin_type) = 0;
public:
void invoke(scope_context& procedure_scope) override
{
auto raw_arg1 = procedure_scope.memory->get(procedure_scope.symbols.get(arg1_traits::param_id()));
auto raw_arg2 = procedure_scope.memory->get(procedure_scope.symbols.get(arg2_traits::param_id()));
this->invoke_impl(arg1_traits::get_from_expression(raw_arg1), arg2_traits::get_from_expression(raw_arg2));
}
};
I know that essentially through template recursion you can essentially iterate through each of the template parameters to do whatever you want to do, but what about the definition of the virtual invoke_impl method? Each of the parameters are derived from the the traits struct, and the call to the method itself also seems not something you could some with template recursion.
How (if) it possible to use a variadic template to allow for a variable number of arguments on this base class as an alternative to just copy/paste this base class with more template arguments?
The final clue was given n314159, this works:
template<ast::builtin_type... Ts>
class builtin_procedure abstract : public builtin_procedure_symbol
{
private:
template<ast::builtin_type T>
typename builtin_type_traits<T>::builtin_type make_arg(scope_context& procedure_scope, int param_id)
{
auto raw_arg = procedure_scope.memory->get(procedure_scope.symbols.get(builtin_type_traits<T>::param_id(param_id++)));
return builtin_type_traits<T>::get_from_expression(raw_arg);
}
protected:
builtin_procedure(const symbol_identifier& identifier, ::symbol_table* runtime_symbol_table): builtin_procedure_symbol(identifier, runtime_symbol_table)
{
auto param_id = 0;
((void) this->register_param(builtin_type_traits<Ts>::param_id(++param_id), Ts), ...);
}
virtual void invoke_impl(typename builtin_type_traits<Ts>::builtin_type...) = 0;
public:
void invoke(scope_context& procedure_scope) override
{
auto param_id = 0;
this->invoke_impl(make_arg<Ts>(procedure_scope, ++param_id)...);
}
};
So, I wrote a small example. I don't think one can do aliasing for variadic templates, so I left that out, but it works without even if it is less nice. So, since I can't use non-integral non-type template parameters, I switched your ast::builtin_type to int, but I think you can reverse that easily enough. The following compiles (but doesn't link, obviously^^).
template<int i>
struct builtin_traits {
static int param_id(int) { return i;}
using builtin_type = int;
};
class builtin_procedure_symbol {
void register_param(int, int);
};
int get(int); // my replacement for procedure_scope.memory->get(procedure_scope.symbols.get
template<int... Ts>
class builtin_procedure : builtin_procedure_symbol{
builtin_procedure(): builtin_procedure_symbol()
{
((void) this->register_param(builtin_traits<Ts>::param_id(1), Ts), ... );
}
virtual void invoke_impl(typename builtin_traits<Ts>::builtin_type...) = 0;
void invoke()
{
auto f = [&](const auto& arg) {
auto raw_arg = get(builtin_traits<arg>::param_id());
return builtin_traits<arg>::get_from_expression(raw_arg);
};
this->invoke_impl(f(Ts)...);
}
};
I hope that helps you. If something is unclear, please ask.
I want to call member function by passing it as template parameter, without using boost is possible. Here is an example off what I tried to do,
class object { void method(); }
{
object object_instance;
...
apply<object:: method>();
...
template<class F>
void apply() { F(object_instance); } // want to call object_instance.F()
}
that does not work, so question is how do I go about binding object method to an object.
Thanks
above is an example, not the real code. I have a bunch of functions differing only in name, but with many parameters, that I want to wrap around in operators.
Something like:
struct foo
{
void bar(void) {}
};
template <typename R, typename C>
R apply(C& pObject, R (C::*pFunc)())
{
return (pObject.*pFunc)();
}
int main(void)
{
foo f;
apply(f, &foo::bar);
}
this.
This is similar to your code, and will allow passing a member function as a template parameter:
class object { public: void method() {} };
object object_instance;
template<void (object::*F)()>
void apply() {
(object_instance.*F)();
}
int main() {
apply<&object::method>();
return 0;
}
As a member function isn't a type or integral value, you can't pass it as a template parameter. You could do what you seem to want by creating a struct which calls the member function, though having object_instance in scope in the template is rather smelly.
What are you actually trying to do?
This example is for rvalue references in c++ox. Does not work on all compilers.
class Sample
{
public:
void fun() { cout << "Sample::fun\n"; }
};
template<typename Function>
void FunCall( Function&& f)
{
f();
}
void RvaluesDemo()
{
FunCall([&]
{
Sample().fun();
});
}