18 May 2018
Motivation
Have direct access to common base class of std::variant
.
struct Base{
int pos;
};
struct A : Base{
int a = 10;
};
struct B : Base{
int b = 20;
};
std::variant<A,B> var;
Base& base = std::get<Base>(var); // can't do this
// can do this, but this will cost you.
Base& base = std::visit([](Base& base) -> Base& {
return base;
}, var);
Final solution
variant_w_base<Base, std::variant<A,B>> var;
Base& base = *var.base();
Base& base = var.get<Base>();
source code
More …
04 May 2018
Sometimes you need enum, and don’t know exact set beforehand.
One could just use int
in conjunction with counter. But it would not be typesafe. Of course, its is better to wrap enum’s id and counter in a dedicated class. Here is my attempt of this concept generalization:
struct Shape : Enum<Shape, char>{};
namespace Shapes{
inline const AddEnum<Shape> circle;
inline const AddEnum<Shape> triangle;
}
latter somewhere…
#include "Shape.h"
namespace Shapes{
inline const AddEnum<Shape> square;
}
More …
17 Nov 2017
Motivation. Extend class, that implement interface I
, with interface derived from I
, without virtual inheritance. C++ does not allow to do static_cast
downcast for class with virtual inheritance.
Have this:
// PURE interfaces per se. No data. All public.
struct IView{
virtual void setOnClick() = 0;
};
struct ITextView : virtual IView {
virtual void setText() = 0;
};
// implementation
struct View : virtual IView {
virtual void setOnClick() override {
std::cout << "setting OnClick!" << std::endl;
}
};
struct TextView : virtual ITextView, virtual View {
virtual void setText() override {
std::cout << "setting text!" << std::endl;
}
};
Without performance overhead of this:
// can do upcast with static_cast
TextView text;
ITextView* i_text = static_cast<ITextView*>(&text);
IView* i_view = static_cast<IView*>(i_text);
// (!) but must use dynamic_cast for downcast
ITextView* text_view = dynamic_cast<ITextView*>(i_view);
More …
06 Nov 2017
Consider that you need queue with thread-safe push_back
and pop_front
operations. Also, consider that you want to consume all available elements, not just one. For example you need this for your home-grown LoopThreadExecutor, or some sort of pending queue:
template<class Message>
struct some_queue{
void process(closure);
void push(Message&& message);
}
More …
29 Oct 2017
Though it is obvious, that using trackable_ptr
allow container’s element access without need of iterator,or index. It may not come at first glance, that you can use trackable_ptr
to do same things, you do with regular iterator (or index access) of any container with contiguous elements storage, like std::vector
.
More …