Disable all class member functions if the class is empty - c++

I have a diagnostic drawing class to graphically plot the status of objects in a multithreaded environment. But this is costing me CPU cycles when I don't run in the diagnostic mode. I don't want to check every line for diagnose mode too. Rather I like to a declare the diagnostic object as empty ( or through some other member functions/ extra variables) and all the diagnostic member functions will be rendered irrelevant. Is this possible? I dont't want to change the existing member functions
bool dmode = true; // want to avoid this
class plot{
void draw();
};
class foo{
void something(){
plot p;
if(dmode) p.draw(); // don't want the checking as plot objects are littered everywhere.
}
};
Edited:
// dmode will be decided only at run time based on my settings configuration

Compile time discard
You may use constexpr:
constexpr bool dmode = true;
//...
if constexpr (dmode) {
Using constexpr this way will make sure the branch is discarded at compile time
It should be noted that this is a c++17 feature, before that you can use macros to discard code at compile time.
A third option is to just rely on compiler optimizations(ie. constant folding), but it is much harder to give any guarentees and might not be feasible for a debug build if that is ever the case.
Runtime solution
Assuming your draw function is virtual - you then need to somehow make a non-virtual function to stick the if into. Then one way to accomplish this is by making the virtual function private.
class plot{
public:
void draw() {
if (!dmode) {
return;
}
do_draw();
}
private://<-- or protected
virtual void do_draw() = 0;//rename in all subclasses
};
However, this is just one way to solve it - without knowing more of the actual case its hard to say which method is more appropriate.

You can do the check inside the draw() function:
void plot::draw() {
if (!dmode) {
return;
}
// Do the actual drawing.
}
If that's not an option for some reason, you could make plot a pure abstract class, and provide two implementations, RealPlot and NullPlot. Then create a function create_plot() that, depending on the value of dmode, returns either a RealPlot or a NullPlot instance.

You have options. Here are some of them:
Concepts - C++20
constexpr bool dmode = true;
class plot
{
public:
void draw() requires (!dmode)
{
/* actual implementation */
}
void draw() requires dmode
{
// empty
}
};
class foo
{
void something()
{
plot p;
p.draw();
}
};
Constexpr if - C++17
constexpr bool dmode = true;
class plot
{
public:
void draw()
{
if constexpr (!dmode)
{
/* actual implementation */
}
}
};
class foo
{
void something()
{
plot p;
p.draw();
}
};
Templated class and an alias - C++11
constexpr bool dmode = true;
template <bool Dmode>
class plot_base
{
public:
void draw()
{
/* actual implementation */
}
};
template <>
class plot_base<true>
{
public:
void draw()
{
// empty
}
};
template <bool Dmode = dmode>
using plot = plot_base<Dmode>;
class foo
{
void something()
{
plot<> p;
p.draw();
}
};
Mock (a.k.a. None of the above)
And ultimately (most likely) none of the solutions are appropriate. It seems to me like what you want is a mock. So look into that.

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

Provide PV function content when constructing object in C++

In Java you can create an object whilst at the same time providing (or overloading) abstract functions within the object, thus:
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Whatever in here
}
};
I really like that way of doing it, and was wondering if there was some similar construct in C++.
Basically I want a base class with a couple of PV functions declared in it (amongst other stuff), and the user to create an instance of that class whilst at the same time providing the body of the PV functions.
I know I could create child classes, but that seems a little clunky for what I need, where each child class would be unique and only be used to make one instance each.
I have thought about providing lamdas to the constructor and using those instead of actual member functions, but that really seems messy and hard for a novice user to get their head around - not to mention that it would be too rigid (I'd also like to be able to override some non-pure virtual functions optionally).
So is child classes the only way to go, or is there some lesser-known construct in some newer C++ standard that I don't know about that could do what I want?
To expand a little - the idea is to have a class like:
class Thread {
// other stuff
public:
virtual void setup() = 0;
virtual void loop() = 0;
// other functions, some virtual but not pure
};
Thread threadOne {
void setup() {
// Init code for this thread
}
void loop() {
// Run code for this thread
}
};
Thread threadTwo {
void setup() {
// Init code for this thread
}
void loop() {
// Run code for this thread
}
};
Obviously not that syntax, but it gives you an idea of how I'd like to use the class.
It's intended to be run on an embedded system with a slimmed-down C++ implementation (it's g++ but without the full STL). End users aren't the brightest bunch, so it has to be kept as simple to understand as possible.
Anonymous child classes are the closest to what I'd like (though still not perfect). I can use CPP macros to help abstract some of the class implementation syntactic sugar which would help.
Here's a compilable construct I have come up with. Is there anything "wrong" with this approach given the constraints above?
#define THREAD(NAME, CONTENT) class : public Thread {\
public:\
CONTENT\
} NAME;
class Thread {
private:
uint32_t stack[256]; // 1kB stack
volatile bool _running;
public:
virtual void setup() = 0;
virtual void loop() = 0;
void start();
void stop();
uint8_t state();
static void spawn(Thread *thr);
void threadRunner();
};
void Thread::spawn(Thread *thread) {
thread->threadRunner();
}
void Thread::start() {
Thread::spawn(this);
}
void Thread::threadRunner() {
_running = true;
setup();
while (_running) {
loop();
}
}
void Thread::stop() {
_running = false;
}
uint8_t Thread::state() {
return 0;
}
THREAD(myThread,
void setup() override {
}
void loop() override {
}
)
void setup() {
myThread.start();
}
void loop() {
}
Obviously it doesn't actually do anything yet - the whole of the threading back-end is a separate issue, and will be ported over from some existing code I wrote a few years back. I am mainly interested in simplifying the interface for the end user.
There is multiple possibilities, but I'd stick with something simple and versatile: callbacks and lambdas instead of virtual function and inheritance.
class ActionListener
{
std::function<void(int)> _action_performed;
public:
template<class CB>
ActionListener(CB cb) : _action_performed(cb) {}
void click() { _action_performed(0); }
};
int main()
{
ActionListener al([](int n) { std::cout << "Action Performed #" << n << "\n"; });
al.click(); // prints "Action Performed #0"
}
live demo
I'd also like to be able to override some non-pure virtual functions optionally
Which, semantically speaking, means providing a default behavior. This is possible:
ActionListener(CB cb) : _action_performed(cb) {} // construct an AL with the given callback
ActionListener() : _action_performed(default_action_performed) {} // construct an AL with a default callback
void default_action_performed(int n) { /*...*/ }
well, as you already mentioned, one way would be child classes.
another way would be providing some std::functions (or lambdas), either in the constructor or have some set functions.
store the function as a member and call this once your "virtual" member function is called: If you want it optional:
class MyBase
{
public:
MyBase();
void SetFunc(const std::function<int()>& myFun)
{
m_myFun = myFun;
}
int MyVirtFunc()
{
if(m_myFun)
{
return m_myFun();
}
else
{
return 42;
}
}
private:
std::function<int()> m_myFun;
}
if you want the functions given mandatory, put them in the constructor:
class MyBase
{
public:
MyBase(const std::function<int()>& myFun)
: m_myFun(myFun) {}
int MyVirtFun() { return m_myFun(); }
private:
const std::function<int()> m_myFun;
}

Is there a better solution than dynamic_cast in that case?

I'm trying to make platform independent code so I'm using OOP. For example, on Windows, Mac OS X, and Linux you can have windows, but on android you have views so I'm trying to abstract this.
I first made a class to represent a window or a view which I called view:
class View
{
public:
virtual ~View()
{}
virtual void display() = 0;
virtual void hide() = 0;
};
Now the problem is that on Android, there is no title for views while on Windows there are so I decided to create another class:
class NameableView : public View
{
public:
virtual void setName(const std::string& name)
};
And then finally implement the classes:
class WindowsView : public NameableView
{
/* Windows implementation */
}
class AndroidView : public View
{
/* Android implementation */
}
Then I need to make some code which sets the name for a view only if it is possible (if it inherits from the NameableView class).
So how can I solve this problem? I first thought about dynamic_cast but I often hear that having too much dynamic_cast is an indication of a design problem. I'm a beginner in C++ so maybe I didn't think the right way and I should change the whole design.
I'm trying to make platform independent code so I'm using OOP.
This is not an optimal approach - polymorphic hierarchies and virtual functions allow different concrete object types that inherit from the same interface to behave differently at run-time, but you know the platform you're going to target at compile-time.
What you should instead do is use static polymorphism and CRTP to provide a common interface that every concrete per-platform implementation must satisfy.
template <typename TDerived>
struct View
{
void display() { static_cast<TDerived&>(*this).display(); }
void hide() { static_cast<TDerived&>(*this).hide(); }
constexpr bool supportsSetView() const
{
return static_cast<TDerived&>(*this).supportsSetView();
}
};
In the case of setName, you should provide a supportsSetView check on every platform that returns true at compile-time if the view can be named. Then you perform that check on the caller side and only invoke setName if the check passes.
Example usage:
#if defined(PLATFORM_ANDROID)
struct AndroidView
{
// ...
constexpr bool supportsSetView() const { return false; }
};
using MyView = View<AndroidView>;
#else if defined(PLATFORM_WINDOWS)
struct WindowsView
{
// ...
constexpr bool supportsSetView() const { return true; }
void setName(std::string x) { /* ... */ }
};
using MyView = View<WindowsView>;
#else
#error "Unsupported platform."
#endif
Caller side:
MyView currentView;
if constexpr(currentView.supportsSetView())
{
currentView.setName("something");
}
As if constexpr(...)'s evaluation occurs at compile-time, the code will only call setName if it is supported by MyView.

Avoiding template verbosity and dynamic polymorphism with types known at compile-time

In my collision/game physics engine, I allow the user to create/specify a preferred spatial parititioning method and a preferred resolution method.
Here's an example with spatial partitioning.
struct SpatialBase
{
virtual void a() = 0;
virtual void b() = 0;
...
};
struct Grid2D : public SpatialBase { ... override a() and b() ... };
struct QuadTree : public SpatialBase { ... override a() and b() ... };
struct World
{
std::vector<std::unique_ptr<Body>> bodies;
std::unique_ptr<SpatialBase> spatial;
...
World(SpatialBase* mSpatial, ...) : spatial(mSpatial), ... { }
};
auto world1{new World{new Grid2D{...}, ...}};
auto world2{new World{new QuadTree{...}, ...}};
This works fine, but the dynamic polymorphism is completely unnecessary. Fact is, a templatized version of World would be too verbose, as a resolution method also needs to be specified, and the Body class must be aware of it.
Example:
auto world1{new World<Grid2D, ImpulseRes>(...)}; // fine
auto& body1{world1.createBody()}; // still fine
void useBody(auto& mBody) { ... }
// illegal! Wish I could use auto& here.
void useBody(Body<Grid2D, ImpulseRes>& mBody) { ... }
// legal - but verbose, and what if the user decides to change
// spatial partitioning or resolution? All code would break.
Is there a way to hide the Grid2D and ImpulseRes types? They only need to be known when the World is created. But Body must also be aware of those types, as it needs a reference to the spatial partitioning method instance and the resolution method instance.
Desired code example:
World world1{new World<Grid2D, ImpulseRes>(...)};
Body& body1{world1.createBody()};
void useBody(Body& mBody) { ... }
I think what you want is a good old-fashioned typedef.
typedef basic_world<grid2d, impulse_res> world;
typedef basic_body<world> body;
world world1(...);
void useBody(body& bdy) { ... };
You may use
template <class TGrid, class TImpulse>
void useBody(Body<TGrid, TImpulse>& mBody) { ... }
or
template <class TBody>
void useBody(TBody& mBody) { ... }
I don't know how your code is partitioned, but if you declare your function after instantiating body1, maybe you could use decltype:
auto& body1 = world1.createBody();
using body_type = decltype(body1);
void useBody(body_type& b) { ... }

Avoiding dynamic_cast in implementation of virtual functions in derived class

Here is some sample code explaining what I am trying to achieve.
Basically, I have an algorithm that depends on some basic operations available in a class. I have defined those operations in a pure abstract base class. I want to apply that algorithm to a variety of objects that provide those operations by deriving classes for the specific objects.
However, the different derived objects are incompatible with one another as far those operations are concerned. My question is whether I can avoid using RTTI to ensure that for example, bool derived2::identical(const base* other2), asserts(or other exit mechanism) where other2 is not of type derived2.
One alternative would be to template the function algorithm on the specific derived object, but that would mean that it's implementation would have to live in a header file which I don't want to do since 1) Changing the algorithm code for test purposes can cause recompilation of large portions of the code 2) The algorithm's implementation would be exposed in the header instead of living nicely in a source file hidden from the end-user.
Header file
#include <list>
class base
{
public:
virtual float difference(const base*) const = 0;
virtual bool identical(const base*) const = 0;
};
class derived1 : public base
{
public:
float difference(const base* other1) const
{
// other1 has to be of type derived1
if(typeid(other1) == typeid(this))
{
// process ...
}
else
{
assert(0);
}
return 1;
}
bool identical(const base* other1) const
{
// other1 has to be of type derived1
if(typeid(other1) == typeid(this))
{
// compare...
}
else
{
assert(0);
}
return true;
}
};
class derived2 : public base
{
public:
float difference(const base* other2) const
{
// process ...
// other2 has to be of type derived2
return 2;
}
bool identical(const base* other2) const
{
// do comparison
// derived1 and derived2 cannot be compared
return true;
}
};
// Declaration
int algorithm(std::list<base*>& members);
Implementation of algorithm Source file
#include "header_file_containing_base"
int algorithm(std::list<base*>& members)
{
// This function only relies on the interface defined in base
// process members;
return 1;
}
Main program
int main()
{
// Create lists of derived1 and derived2
// Run algorithm on these lists
}
You could use double dispatch (http://en.wikipedia.org/wiki/Double_dispatch)
Well, there is one simple thing: store the real type as a member.
An enum, grouping all the types. It'll become cumbersome if you have a lot of them.
A Factory to generate ids (using templates to only generate one id per item)
...
I'll illustrate the factory id:
class IdFactory
{
public:
template <class T>
static size_t GetId(T const&) // argument deduction
{
static size_t const Id = GetIdImpl();
return Id;
}
private:
static size_t GetIdImpl()
{
static size_t Id = 0;
return ++Id;
}
}; // class IdFactory
And you can use it like such:
class Base
{
public:
explicit Base(size_t id): mId(id) {}
size_t const mId; // meaningless to change it afterward...
private:
};
class Derived: public Base
{
public:
explicit Derived(): Base(IdFactory::GetId(*this)) {}
};
Then you can use the mId member for testing. Note that since it's const it can be exposed... otherwise you can create an inline const getter...
float Derived::difference(const Base& rhs)
{
assert( IdFactory::GetId(*this) == rhs.mId );
// ...
}
The cost here is negligible:
GetId is inlined, thus no function call
GetId is lazily initialized, apart for the initialization it amounts to checking that the static member has been initialized: it's typically implemented as a if statement which condition always evaluate to true (apart from the first time).
== is normally fast ;)
The only downside is that you actually need to make sure that you correctly initialize the ids.
There is also a no-storing solution, which involves a virtual function call:
class Other: public Base
{
public:
virtual size_t id() const { return IdFactory::GetId(*this); }
};
It's easier to put in practice because not storing a const member means that you don't have to write the assignment yourself.
You could use a templated function. With templates it is possible to add more classes later without the need to change the original classes, by just adding another template function in another header file. If the only problem is the compile speed - you can implement the template function in a source file apart from the header and use explicit template instanciation.