Does C++0x support Anonymous Inner Classes? - c++

Say I have listeners built in C++98, they are abstract and must for example implement ActionPerformed. In C++0x is there a way to do similar to Java:
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
Thanks

Not exactly, but you can do something close with Lambdas.
i.e.:
class ActionListener
{
public:
typedef std::function<void(ActionEvent&)> ActionCallback;
public:
ActionListener( ActionCallback cb )
:_callback(cb)
{}
void fire(ActionEvent& e )
{
_callback(e);
}
private:
ActionCallback _callback;
};
..
button.addActionListener( new ActionListener(
[]( ActionEvent& e )
{
...
}
));

No you can't do that.
If you give up on "similar to Java", though, and just use a functor, you'll find C++11 lambdas very helpful.

This is C++, not Java, so writing C++ like Java won't work well.
Anyway, you could create an adaptor function. Suppose
typedef int ActionEvent; // <-- just for testing
class ActionListener
{
public:
virtual void actionPerformed(const ActionEvent& event) = 0;
};
Then we could write a templated subclass of ActionListener that wraps a function object:
#include <memory>
template <typename F>
class ActionListenerFunctor final : public ActionListener
{
public:
template <typename T>
ActionListenerFunctor(T&& function)
: _function(std::forward<T>(function)) {}
virtual void actionPerformed(const ActionEvent& event)
{
_function(event);
}
private:
F _function;
};
template <typename F>
std::unique_ptr<ActionListenerFunctor<F>> make_action_listener(F&& function)
{
auto ptr = new ActionListenerFunctor<F>(std::forward<F>(function));
return std::unique_ptr<ActionListenerFunctor<F>>(ptr);
}
and then use make_action_listener to wrap a lambda, e.g ( http://ideone.com/SQaLz ).
#include <iostream>
void addActionListener(std::shared_ptr<ActionListener> listener)
{
ActionEvent e = 12;
listener->actionPerformed(e);
}
int main()
{
addActionListener(make_action_listener([](const ActionEvent& event)
{
std::cout << event << std::endl;
}));
}
Note that this is far from idiomatic C++, where in addActionListener() you should simply take a const std::function<void(const ActionEvent&)>&, or even a template parameter for maximum efficiency, and supply the lambda directly.

I think we can do this in C++ using lambdas
button.addActionListener([]()->ActionListener*{ struct A: ActionListener {
void actionPerfored(ActionEvent e)
{
// do something.
}
}; return new A;}());
It should be easy to wrap this up in a macro.

Related

Automatic generate member functions depending on inherited class template

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);
}

Derive (virtual) function arguments in variadic template class

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.

c++ virtual templated function

Understandably, functions can not be both templated and virtual.
But there may be a super smart design pattern out there that would do.
My goal is to have a function which looks like as :
void configure(const Configuration &config){
double stuff = config.get<double>("stuff");
int thing = config.get<int>("thing");
// rest of the code
}
Ideally, I could pass various configuration object, e.g. object that read from a file or from a database.
Here a (stripped to minimum) example of a concrete config class using yaml-cpp (I guess understandable even if you do not know yaml-cpp):
class YAML_config : public Configuration {
public:
YAML_config(std::string file_path){
this->node = YAML::LoadFile(file_path);
}
template<typename T> T get(std::string key){
return this->node[key].as<T>();
}
private:
YAML::Node node;
Question is: what would be the suitable code for the class Configuration ?
Here some invalid code that shows the intend:
class Configuration {
virtual template<typename T> T get(std::string key)=0;
}
If all this is just a bad start, any other approach I should look into ? I checked for "type erasure", but that did not seem to help (or did I miss something ?)
It looks like you have a small-ish set of possible types, so I suggest a set of virtual functions grouped together with a non-virtual dispatching template:
template <class T>
struct tag { };
class Configuration {
public:
template <class T>
T get(std::string key) {
return get_(tag<T>{}, std::move(key));
}
protected:
virtual int get_(tag<int>, std::string key) = 0;
virtual double get_(tag<double>, std::string key) = 0;
virtual std::string get_(tag<std::string>, std::string key) = 0;
};
class YAML_config : public Configuration {
int get_(tag<int>, std::string key) override { /* ... */ }
double get_(tag<double>, std::string key) override { /* ... */ }
std::string get_(tag<std::string>, std::string key) override { /* ... */ }
};
Usage:
YAML_config cfg;
auto s = cfg.get<int>("hello");
See it live on Coliru
But we lost the ability to declare YAML_config::get as a template -- types aside, the implementations are all the same, but we can't override a virtual function with a template.
So, now that we bridged the gap from templates to virtual functions to achieve polymorphism, let's bridge the gap from virtual functions back to templates to get our nice API back. This can be done by slotting in a CRTP between the Configuration and YAML_config classes: its role will be to generate the overriden functions.
Note: the get_ virtual functions are now called getBridge. I have added a dash of macros to cut down on repetition. These can be further factored out with Boost.PP, for example.
class ConfigurationBase {
// ...
#define DECLARE_CONFIG_BRIDGE(T) \
virtual T getBridge(tag<T>, std::string key) = 0;
DECLARE_CONFIG_BRIDGE(int)
DECLARE_CONFIG_BRIDGE(double)
DECLARE_CONFIG_BRIDGE(std::string)
#undef DECLARE_CONFIG_BRIDGE
};
template <class Derived>
class Configuration : public ConfigurationBase {
// Hide ConfigurationBase::get so we don't get
// infinite recursion if we forget an implementation
// in the derived class.
template <class>
void get(...) = delete;
#define OVERRIDE_CONFIG_BRIDGE(T) \
T getBridge(tag<T>, std::string key) override { \
return dThis()->template get<T>(std::move(key)); \
}
OVERRIDE_CONFIG_BRIDGE(int)
OVERRIDE_CONFIG_BRIDGE(double)
OVERRIDE_CONFIG_BRIDGE(std::string)
#undef OVERRIDE_CONFIG_BRIDGE
Derived *dThis() {
return static_cast<Derived*>(this);
}
};
class YAML_config : public Configuration<YAML_config> {
public:
template <class T>
T get(std::string) {
return {};
}
};
See it live on Coliru
I have adapted my answer to a similar question from earlier today which uses type erasure and RTTI to get the effect of a virtual templated function. As I noted there, Boost.TypeIndex can be used if you cannot or do not want to use RTTI.
The basic implementation looks something like this (just fill in your YAML library stuff):
#include <functional>
#include <typeindex>
#include <unordered_map>
class config {
public:
template <typename T>
T get(char const* key) {
T value = {};
auto it = getters.find(type_index<T>());
if (it != getters.end()) {
it->second(&value, key);
}
return value;
}
protected:
template <typename T, typename Getter>
void register_getter(Getter getter) {
getters[type_index<T>()] = [getter](void* value, char const* key) {
*static_cast<T*>(value) = getter(key);
};
}
private:
template <typename T>
static std::type_index type_index() {
return std::type_index(typeid(std::remove_cv_t<T>));
}
std::unordered_map<std::type_index, std::function<void (void*, char const*)>> getters;
};
Usage would look like this (note that you could use composition instead of inheritance if you don't actually need config to be a base class):
#include <iostream>
class yaml_config : public config {
public:
yaml_config() {
register_getter<int>([](char const* key) {
return 42;
});
register_getter<float>([](char const* key) {
return 3.14f;
});
}
};
int main() {
yaml_config cfg;
std::cout << cfg.get<int>("foo") << "\n";
std::cout << cfg.get<float>("bar") << "\n";
std::cout << cfg.get<short>("baz") << "\n";
}
Output:
42
3.14
0
In this particular implementation, T must be default constructible; if this is unacceptable, you could use std::any instead of void*. In addition, a default value is returned in the case where an appropriate getter is not registered. You may want to throw an exception, or return a std::optional<T> or std::pair<T, bool>, to distinguish these cases from a default value actually being mapped to a specific key.
This solution has the advantage that sub-classes can register getters for any type. However, there are certainly more efficient solutions if you know the subset of types that config::get<T> needs to work with.

multi-signatures signal management in user classes

I'm very familiar with Qt and I know that we cannot have a similar synthax because we don't have the MOC part here. However I'm trying to have a signal creation management to simplify the declaration of a signal and the connection to it, inside my classes.
this is schematicly what I'm doing now
class Foo
{
public:
void connectMove(boost::signal<void(int)>::slot_type slot)
void connectRotate(boost::signal<void(double)>::slot_type slot)
private:
boost::signal<void(int)> m_signalMove;
boost::signal<void(double)> m_signalRotate;
};
and this is basicaly what I would like to do (UPPERCASE = missing part)
class SignalManager
{
public:
typedef boost::unrodered_map<std::string, GENERIC_SIGNAL *> MapSignal;
public:
template <typename Sig>
bool connect(const std::string& strSignalName, boost::signal<Sig>::slot_type slot)
{
// simplyfied... :
(*m_mapSignal.find(strSignalName))->connect(slot);
}
template <typename Sig>
bool disconnect(const std::string& strSignalName, boost::signal<Sig>::slot_type slot)
{
// simplyfied... :
(*m_mapSignal.find(strSignalName))->disconnect(slot);
}
protected:
bool call(const std::string& strSignalName, SIGNAL_ARGS)
{
(*m_mapSignal.find(strSignalName))(SIGNAL_ARGS);
}
template <typename Sig>
void delareSignal(const std::string& strSignalName)
{
m_mapSignals.insert(MapSignal::value_type(strSignalName, new boost::signal<Sig>()));
}
void destroySignal(const std::string& strSignalName)
{
// simplyfied... :
auto it = m_mapSignal.find(strSignalName);
delete *it;
m_mapSignal.erase(it);
}
private:
MapSignal m_mapSignals;
};
class Foo : public SignalManager
{
public:
Foo(void)
{
this->declareSignal<void(int)>("Move");
this->declareSignal<void(double)>("Rotate");
}
};
class Other : public boost::signals::trackable
{
public:
Other(Foo *p)
{
p->connect("Move", &Other::onMove);
p->connect("Rotate", &Other::onRotate);
}
void onMove(int i)
{
/* ... */
}
void onRotate(double d)
{
/* ... */
}
};
I think I could resolve the "SIGNAL_ARGS" part with boost::functions_traits<>, but i don't know how to go around the abstract signal type.
1/ Is what I want even possible ?
2/ Is this a good approach ? (I know I will have some overhead due to the unordered_map.find, esspecily when I use this->call("signalname", ...), but I think it shouldn't be too significant)
3/ If this is not possible or not a good approach, do you have any other suggestions ?
I resolved my problem by wrapping boost::signals and having a boost::shared_ptr<IWrapperSignal> instead of my GENERIC_SIGNAL.
The arguments probnlem was also resolved using boost::function_traits<T>::arg_type.
I don't know if it's the best way to do that, but it's working fine, and it is more simple for the user to declare signals in the classes that inherit this SignalManager.

Object-Oriented Callbacks for C++?

Is there some library that allows me to easily and conveniently create Object-Oriented callbacks in c++?
the language Eiffel for example has the concept of "agents" which more or less work like this:
class Foo{
public:
Bar* bar;
Foo(){
bar = new Bar();
bar->publisher.extend(agent say(?,"Hi from Foo!", ?));
bar->invokeCallback();
}
say(string strA, string strB, int number){
print(strA + " " + strB + " " + number.out);
}
}
class Bar{
public:
ActionSequence<string, int> publisher;
Bar(){}
invokeCallback(){
publisher.call("Hi from Bar!", 3);
}
}
output will be:
Hi from Bar! 3 Hi from Foo!
So - the agent allows to to capsule a memberfunction into an object, give it along some predefined calling parameters (Hi from Foo), specify the open parameters (?), and pass it to some other object which can then invoke it later.
Since c++ doesn't allow to create function pointers on non-static member functions, it seems not that trivial to implement something as easy to use in c++. i found some articles with google on object oriented callbacks in c++, however, actually i'm looking for some library or header files i simply can import which allow me to use some similarily elegant syntax.
Anyone has some tips for me?
Thanks!
The most OO way to use Callbacks in C++ is to call a function of an interface and then pass an implementation of that interface.
#include <iostream>
class Interface
{
public:
virtual void callback() = 0;
};
class Impl : public Interface
{
public:
virtual void callback() { std::cout << "Hi from Impl\n"; }
};
class User
{
public:
User(Interface& newCallback) : myCallback(newCallback) { }
void DoSomething() { myCallback.callback(); }
private:
Interface& myCallback;
};
int main()
{
Impl cb;
User user(cb);
user.DoSomething();
}
People typically use one of several patterns:
Inheritance. That is, you define an abstract class which contains the callback. Then you take a pointer/reference to it. That means that anyone can inherit and provide this callback.
class Foo {
virtual void MyCallback(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> ptr;
void something(...) {
ptr->MyCallback(...);
}
Base& SetCallback(Foo* newfoo) { ptr = newfoo; return *this; }
Foo* GetCallback() { return ptr; }
};
Inheritance again. That is, your root class is abstract, and the user inherits from it and defines the callbacks, rather than having a concrete class and dedicated callback objects.
class Foo {
virtual void MyCallback(...) = 0;
...
};
class RealFoo : Foo {
virtual void MyCallback(...) { ... }
};
Even more inheritance- static. This way, you can use templates to change the behaviour of an object. It's similar to the second option but works at compile time instead of at run time, which can yield various benefits and downsides, depending on the context.
template<typename T> class Foo {
void MyCallback(...) {
T::MyCallback(...);
}
};
class RealFoo : Foo<RealFoo> {
void MyCallback(...) {
...
}
};
You can take and use member function pointers or regular function pointers
class Foo {
void (*callback)(...);
void something(...) { callback(...); }
Foo& SetCallback( void(*newcallback)(...) ) { callback = newcallback; return *this; }
void (*)(...) GetCallback() { return callback; }
};
There are function objects- they overload operator(). You will want to use or write a functional wrapper- currently provided in std::/boost:: function, but I'll also demonstrate a simple one here. It's similar to the first concept, but hides the implementation and accepts a vast array of other solutions. I personally normally use this as my callback method of choice.
class Foo {
virtual ... Call(...) = 0;
virtual ~Foo();
};
class Base {
std::auto_ptr<Foo> callback;
template<typename T> Base& SetCallback(T t) {
struct NewFoo : Foo {
T t;
NewFoo(T newt) : t(newt) {}
... Call(...) { return t(...); }
};
callback = new NewFoo<T>(t);
return this;
}
Foo* GetCallback() { return callback; }
void dosomething() { callback->Call(...); }
};
The right solution mainly depends on the context. If you need to expose a C-style API then function pointers is the only way to go (remember void* for user arguments). If you need to vary at runtime (for example, exposing code in a precompiled library) then static inheritance can't be used here.
Just a quick note: I hand whipped up that code, so it won't be perfect (like access modifiers for functions, etc) and may have a couple of bugs in. It's an example.
C++ allows function pointers on member objects.
See here for more details.
You can also use boost.signals or boost.signals2 (depanding if your program is multithreaded or not).
There are various libraries that let you do that. Check out boost::function.
Or try your own simple implementation:
template <typename ClassType, typename Result>
class Functor
{
typedef typename Result (ClassType::*FunctionType)();
ClassType* obj;
FunctionType fn;
public:
Functor(ClassType& object, FunctionType method): obj(&object), fn(method) {}
Result Invoke()
{
return (*obj.*fn)();
}
Result operator()()
{
return Invoke();
}
};
Usage:
class A
{
int value;
public:
A(int v): value(v) {}
int getValue() { return value; }
};
int main()
{
A a(2);
Functor<A, int> fn(a, &A::getValue);
cout << fn();
}
Joining the idea of functors - use std::tr1::function and boost::bind to build the arguments into it before registering it.
There are many possibilities in C++, the issue generally being one of syntax.
You can use pointer to functions when you don't require state, but the syntax is really horrid. This can be combined with boost::bind for an even more... interesting... syntax (*)
I correct your false assumption, it is indeed feasible to have pointer to a member function, the syntax is just so awkward you'll run away (*)
You can use Functor objects, basically a Functor is an object which overloads the () operator, for example void Functor::operator()(int a) const;, because it's an object it has state and may derive from a common interface
You can simply create your own hierarchy, with a nicer name for the callback function if you don't want to go the operator overloading road
Finally, you can take advantage of C++0x facilities: std::function + the lambda functions are truly awesome when it comes to expressiveness.
I would appreciate a review on lambda syntax ;)
Foo foo;
std::function<void(std::string const&,int)> func =
[&foo](std::string const& s, int i) {
return foo.say(s,"Hi from Foo",i);
};
func("Hi from Bar", 2);
func("Hi from FooBar", 3);
Of course, func is only viable while foo is viable (scope issue), you could copy foo using [=foo] to indicate pass by value instead of pass by reference.
(*) Mandatory Tutorial on Function Pointers