I have an abstract class:
class A
{
public:
bool loaded_;
virtual int load() = 0;
}
And several derived classes :
class B:public A
{
public:
int load();
static B& instance();
}
class C:public A
{
public:
int load();
static C& instance();
}
The fact is that the code inside ::instance() methods is the same for each class :
static B& B::instance()
{
static B instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
static C& C::instance()
{
static C instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
I would like to factorize this ::instance method, but given that it uses the virtual method ::load, i cannot define it in the class A.
Theoretically, i know it's weird since the class A should have 0 instance and B,C should have 1 instance but it also makes sense that this code should be factorized.
How would you solve that problem ?
You could make instance() a free function template:
template<class T>
T& instance()
{
static T instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
Then you can use it like this:
instance<B>().do_stuff()
This is a common usage of the CRTP, define the function that creates the instance in the template and then instantiate it in each type:
struct A {
virtual ~A() {} // don't forget to make your destructor virtual!
virtual void load() = 0;
};
template <typename T>
struct instance_provider {
static T& instance() { /* implementation */ }
};
struct B : A, instance_provider<B> {
virtual void load();
};
struct C : A, instance_provider<C> {
virtual void load();
};
Related
I created a Foo class which needs to be used only as a shared pointer, so I made the constructor private to prevent client to use Foo directly:
#include <memory>
class Foo {
public:
static std::shared_ptr<Foo> Create() {
return std::shared_ptr<Foo>(new Foo());
}
std::shared_ptr<Foo> Copy() {
return std::shared_ptr<Foo>(new Foo(*this));
}
private:
Foo() = default;
};
I then updated Foo to use the CRTP pattern so I could have a class Bar inherit from it without having to re-define the Create() and Copy() methods:
#include <memory>
template <class Self>
class Foo {
public:
template <class... Args>
static std::shared_ptr<Self> Create(Args&&... args) {
return std::shared_ptr<Self>(new Self(std::forward<Args>(args)...));
}
virtual std::shared_ptr<Self> Copy() {
return std::shared_ptr<Self>(new Self(*this));
}
private:
Foo() = default;
};
class Bar : public Foo<Bar> {};
Then I needed to provide a non-templated FooBase interface that would provide some functions shared by all derived classes:
#include <memory>
class FooBase {
public:
virtual void DoSomething() =0;
};
template <class Self>
class Foo : public FooBase {
public:
template <class... Args>
static std::shared_ptr<Self> Create(Args&&... args) {
return std::shared_ptr<Self>(new Self(std::forward<Args>(args)...));
}
virtual std::shared_ptr<Self> Copy() {
return std::shared_ptr<Self>(new Self(*this));
}
virtual void DoSomething() override { }
private:
Foo() = default;
};
class Bar : public Foo<Bar> {
public:
virtual void DoSomething() override { }
};
Now I also need to expose the Copy() method to the Foobar interface, but I cannot find any elegant ways to do it without changing the name for the interface (e.g. CopyBase())
#include <memory>
class FooBase {
public:
virtual void DoSomething() =0;
// Expose Copy method by using a different name.
virtual std::shared_ptr<FooBase> CopyBase() const =0;
};
template <class Self>
class Foo : public FooBase {
public:
template <class... Args>
static std::shared_ptr<Self> Create(Args&&... args) {
return std::shared_ptr<Self>(new Self(std::forward<Args>(args)...));
}
virtual std::shared_ptr<FooBase> CopyBase() const override {
return Copy();
}
virtual std::shared_ptr<Self> Copy() {
return std::shared_ptr<Self>(new Self(*this));
}
virtual void DoSomething() override { }
private:
Foo() = default;
};
class Bar : public Foo<Bar> {
public:
virtual void DoSomething() override { }
};
This code works, but I feel that there must be a better way to do this. I exposed my thinking process in details as I suspect that the flaws might be in the design, so I'm wondering if anyone could help me gain a different perspective on this issue.
Thanks for your time!
covariant return type is only possible with regular pointer or reference, not with smart pointer.
Additional issue with CRTP is that class is incomplete, so covariance cannot be used neither.
The traditional way is indeed to split the clone in 2 part, a virtual one (private) and a public (non-virtual) one, something like:
template <typename Derived, typename Base>
class Clonable : public Base
{
public:
template <class... Args>
static std::shared_ptr<Derived> Create(Args&&... args) {
return std::shared_ptr<Derived>(new Derived(std::forward<Args>(args)...));
}
std::shared_ptr<Derived> Clone() const {
return std::shared_ptr<Derived>(static_cast<Derived*>(vclone()));
}
private:
// Cannot use covariant-type `Derived*` in CRTP as Derived is not complete yet
Base* vclone() const override {
return new Derived(static_cast<const Derived&>(*this));
}
};
And then
class FooBase {
public:
virtual ~FooBase() = default;
virtual void DoSomething() = 0;
// Expose Copy method by using a different name.
std::shared_ptr<FooBase> Clone() const { return std::shared_ptr<FooBase>(vclone()); }
private:
virtual FooBase* vclone() const = 0;
};
class Bar : public Clonable<Bar, FooBase> {
public:
void DoSomething() override { }
};
Demo
I have a class MyClass (with several virtual functions) that performs operations on an object called MyType.
The class MyClassImpl inherits MyClass and implements the virtual functions, but I need to add additional members to MyType, but I don't want to modify the class MyType (instead I want to keep it generic).
Now, if I make a MyTypeImpl and inherit MyType, I can add members. But, how do I make the non virtual functions in MyClassImpl (inherited from MyClass) use the new MyTypeImpl?
The only way I can think is to make MyClass use MyTypeImpl but I want to avoid using the implementation in the generic class because I might use various different implementations.
Here is a simple example of what the classes might look like. Of course, the code will not compile because the methods and members added in MyTypeImpl and not MyType.
class MyType {
public:
void increment() {
data_++;
}
protected:
int data_ = 0;
};
class MyClass {
public:
void alg() {
sub_routine_1();
sub_routine_2();
modify_mytype();
};
protected:
MyType mytype_;
virtual void sub_routine_1() = 0;
virtual void sub_routine_2() = 0;
void modify_mytype() {
mytype_.increment();
};
};
class MyTypeImpl : public MyType {
public:
void decrement() {
data_--;
is_decremented = true;
};
protected:
bool is_decremented = false;;
};
class MyClassImpl : public MyClass{
public:
void print() {
mytype_.print();
};
protected:
virtual void sub_routine_1() {
//do algorithm things here
mytype_.increment();
mytype_.increment();
};
virtual void sub_routine_2() {
//do more algorithm things here
mytype_.decrement();
mytype_.decrement();
};
};
After seeing your example I see now that you just want to extend the functionality of that class without modifying the original class. If you need to add additional functions, but you don't want to change the type that is stored in MyClass there isn't any way I know of to make that happen without at least modifying MyType to include virtual functions for the functions you want to call.
You also need to make MyClass take a pointer to MyType so you can use polymorphism and make the calls resolve to the correct implementation:
Dynamic Polymorphism Solution:
#include <iostream>
class MyType {
public:
virtual void increment() {
data_++;
}
// To be implemented by implementation class
virtual void print() = 0;
// To be implemented by implementation class
virtual void decrement() = 0;
protected:
int data_ = 0;
};
class MyTypeImpl : public MyType
{
public:
void print() {
std::cout << 42 << std::endl;
}
void decrement() {
data_--;
is_decremented = true;
};
protected:
bool is_decremented = false;;
};
class MyClass {
public:
MyClass(MyType* mytype)
: mytype_(mytype)
{}
void alg() {
sub_routine_1();
sub_routine_2();
modify_mytype();
};
protected:
MyType* mytype_;
virtual void sub_routine_1() = 0;
virtual void sub_routine_2() = 0;
void modify_mytype() {
mytype_->increment();
};
};
class MyClassImpl : public MyClass{
public:
MyClassImpl(MyType* mytype)
: MyClass(mytype)
{}
void print() {
mytype_->print();
};
protected:
virtual void sub_routine_1() {
//do algorithm things here
mytype_->increment();
mytype_->increment();
};
virtual void sub_routine_2() {
//do more algorithm things here
mytype_->decrement();
mytype_->decrement();
};
};
int main()
{
MyType* mytype = new MyTypeImpl();
MyClass* myclass = new MyClassImpl(mytype);
// Prints "42"
myclass->print();
// Do other stuff with "myclass"
delete myclass;
delete mytype;
}
Note, I am only using a raw pointer in this example for increased clarity. It is highly recommended that you don't use new and delete and use smart pointers to manage the lifetime of your pointers instead.
Static Polymorphism Solution:
Not that the design of this solution is actually any better, but I think this is closer to what you are actually looking for because it doesn't require modifying the MyType class directly. Also the only modification needed for MyClass is to make it a template class:
#include <iostream>
class MyType {
public:
virtual void increment() {
data_++;
}
protected:
int data_ = 0;
};
class MyTypeImpl : public MyType
{
public:
void print() {
std::cout << data_ << std::endl;
}
void decrement() {
data_--;
is_decremented = true;
};
protected:
bool is_decremented = false;
};
template <typename T>
class MyClass {
public:
void alg() {
sub_routine_1();
sub_routine_2();
modify_mytype();
};
protected:
T mytype_;
virtual void sub_routine_1() = 0;
virtual void sub_routine_2() = 0;
void modify_mytype() {
mytype_.increment();
};
};
template <typename T>
class MyClassImpl : public MyClass<T> {
public:
void print() {
this->mytype_.print();
};
protected:
virtual void sub_routine_1() {
//do algorithm things here
this->mytype_.increment();
this->mytype_.increment();
};
virtual void sub_routine_2() {
//do more algorithm things here
this->mytype_.decrement();
this->mytype_.decrement();
};
};
int main()
{
// Use the template to get the correct implementation
MyClassImpl<MyTypeImpl> myclass;
myclass.alg();
myclass.print();
// Do other stuff with my class
}
How to do multiple inheritance just for function?
must share data of the base class
no virtual function (assume that vtable is expensive)
avoid virtual inheritance
implementation must be able to reside in .cpp
c++14 is allowed
Here are similar questions :-
Multiple inheritance in diamond shape with functions only - use virtual inheritance. Virtual inheritance is generally bad and expensive.
multiple inheritance without virtual inheritance - focuses on syntax and compiling rather than programming technique.
Multilevel inheritance in c++ (CRTP) , CRTP and multilevel inheritance , Eliminate redundancy with CRTP and multiple inheritance (C++03) and Using CRTP with virtual inheritance - implementation must be in header
Here is a sample code (coliru demo) :-
class O{
protected: int database=0;
};
class A : public O{
public: void print(){
std::cout<<database<<std::endl;
}
};
class B : public O{
public: void set(int s){
database=s+1;
}
};
class AB : public O{
public: void print(){//duplicate
std::cout<<database<<std::endl;
}
public: void set(int s){//duplicate
database=s+1;
}
};
//AB ab; ab.set(1); ab.print(); // would print 2
Here is my attempt (wandbox demo). I abuse CRTP :( :-
class O{
public: int database=0;
};
template<class T>class OA{
public: void print(){
std::cout<<static_cast<T*>(this)->database<<std::endl;
}
};
template<class T>class OB{
public: void set(int s){
static_cast<T*>(this)->database=s+1;
}
};
class A :public O,public OA<A>{};
class B :public O,public OB<B>{};
class AB :public O,public OA<AB>,public OB<AB>{};
It works, but it looks inelegant.
Furthermore, implementation must be in header (because OA and OB are template classes).
Are there better approaches? Or is this the way to go?
Sorry if it is too newbie question or already asked. I am a C++ beginner.
Edit
Give extended example of using please.
In ECS, it would be useful in some cases :-
class O{
protected: EntityHandle e;
};
class ViewAsPhysic : public O{ //A
public: void setTransform(Transformation t){
Ptr<PhysicTransformComponent> g=e;
g->transform=t;
}
};
class ViewAsLight : public O{ //B
public: void setBrightness(int t){
Ptr<LightComponent> g=e;
g->clan=t;
}
};
class ViewAsLightBlock : public O{ //AB
//both functions
};
The problem here is that the database field is member of class O. So without virtual inheritance, A and B will have each their own copy of database. So you must find a way to force A and B to share same value. You could for example use a reference field initialized in a protected constructor:
#include <iostream>
class O{
int _db;
protected: int &database;
O(): database(_db) {};
O(int &db): database(db) {};
};
class A : public O{
public: void print(){
std::cout<<database<<std::endl;
}
A() {} // public default ctor
protected: A(int& db): O(db) {}; // protectect ctor
};
class B : public O{
public: void set(int s){
database=s+1;
}
B() {} // public default ctor
protected: B(int& db): O(db) {}; // protectect ctor
};
class AB : public A, public B {
int _db2;
public: AB(): A(_db2), B(_db2) {}; // initialize both references to same private var
};
int main() {
AB ab;
ab.set(1);
ab.print();
return 0;
}
displays as expected:
2
Above code uses no virtual inheritance, no virtual function and no templates, so method can safely implemented in cpp files. The class AB actually uses methods from its both parents and has still a coherent view on its underlying data. In fact it simulates an explicit virtual inheritance by building the common data in the most derived class and injecting in through protected constructors in its parents.
Something like this?
must share data of the base class - check
no virtual function (assume that vtable is expensive) - check
avoid virtual inheritance - check
implementation must be able to reside in .cpp- check
c++14 is allowed - check. c++11 used.
#include <iostream>
class O {
protected:
int database = 0;
};
/*
* the concept of implementing print for a base class
*/
template<class...Bases>
struct implements_print : Bases... {
void print() const {
std::cout << this->database << std::endl;
}
};
/*
* The concept of implementing set for a base class
*/
template<class...Bases>
struct implements_set : Bases... {
void set() {
++this->database;
}
};
struct B : implements_set<O> {
};
struct A : implements_print<O> {
};
struct AB : implements_set<implements_print<O>> {
};
int main() {
A a;
a.print();
B b;
b.set();
AB ab;
ab.set();
ab.print();
}
Another way, using composition and an access class to provide access to the protected member. This example shows how to defer the work on database to another compilation unit:
#include <iostream>
/*
* this stuff in cpp
*/
namespace implementation
{
void print(const int& database) {
std::cout << database << std::endl;
}
void set(int& database) {
++database;
}
}
/*
* this stuff in header
*/
struct OAccess;
class O {
private:
int database = 0;
friend OAccess;
};
struct OAccess {
template<class Host>
constexpr decltype(auto) database(Host &host) const { return (host.database); } // note: () makes reference
template<class Host>
constexpr decltype(auto) database(Host const &host) const { return (host.database); } // note: () makes reference
};
/*
* the concept of implementing print for a derived class
*/
template<class Host>
struct implements_print {
void print() const {
OAccess access;
implementation::print(access.database(self()));
}
private:
decltype(auto) self() const { return static_cast<Host const &>(*this); }
};
/*
* The concept of implementing set for a derived class
*/
template<class Host>
struct implements_set {
void set() {
OAccess access;
implementation::set(access.database(self()));
}
private:
decltype(auto) self() { return static_cast<Host &>(*this); }
};
template<template<class> class...Impls>
struct OImpl : Impls<OImpl<Impls...>> ..., O {
};
using B = OImpl<implements_set>;
using A = OImpl<implements_print>;
using AB = OImpl<implements_print, implements_set>;
int main() {
A a;
a.print();
B b;
b.set();
AB ab;
ab.set();
ab.print();
}
We start with defining the concepts of things that can print and things that can be set:
namespace util {
template<class Base, class Derived, class R=void>
using if_base = std::enable_if_t< std::is_base_of< std::decay_t<Base>, std::decay_t<Derived>>::value, R >;
struct stub {};
}
namespace concepts {
template<class Token>
void do_print(Token, util::stub const&)=delete;
template<class Token>
void do_set(Token, util::stub&, int)=delete;
struct has_print {
struct token { friend struct has_print; private: token(int){} };
template<class T>
friend util::if_base<has_print, T> print(T const& t) {
do_print(get_token(), t);
}
private: static token get_token() { return 0; }
};
struct has_set {
struct token { friend struct has_set; private: token(int){} };
template<class T>
friend util::if_base<has_set, T> set(T& t, int x) {
do_set(get_token(),t, x);
}
private: static token get_token() { return 0; }
};
}
We then declare O and the operations you can support on it:
namespace DB {
class O;
void do_print(::concepts::has_print::token, O const& o);
void do_set(::concepts::has_set::token, O& o, int);
class O{
protected: int database=0;
friend void do_print(::concepts::has_print::token, O const&);
friend void do_set(::concepts::has_set::token, O&, int);
};
class A : public O, public concepts::has_print {
};
class B : public O, public concepts::has_set {
};
class AB : public O, public concepts::has_print, concepts::has_set {
};
}
void DB::do_print(::concepts::has_print::token, O const& o ) { std::cout << o.database << std::endl; }
void DB::do_set(::concepts::has_set::token, O& o, int x) { o.database = x+1; }
The hard part of this is the access control.
I ensure it isn't possible to call do_set except through has_set::set.
That is what all those tokens are about. You can strip them out and their overhead if you are willing to just say "don't call the do_ functions" (and maybe give them another name, like private_impl_set).
Live example.
To start discussion.
class O
{
// no virtual destructor. So cant use polymorphic deletion
// like :
// O *o = new AB;
// delete o;
protected: int database=0;
};
class A : virtual public O{
public: void print(){
std::cout<<database<<std::endl;
}
};
class B : virtual public O{
public: void set(int s){
database=s+1;
}
};
class AB : protected A, protected B{}; // no vtable
void foo() {
AB ab;
ab.print(); // won't perform virtual call.
}
How can you switch between multiple sets of static methods where each set is required to have the same signature? The natural way seemed to implement a common interface, but there is no virtual static method in C++.
You can lift the static property to a single instance and use a template:
template<typename Derived>
class StaticInterface {
protected:
StaticInterface() {}
public:
virtual ~StaticInterface() {}
static Derived& instance() {
Derived theInstance;
return theInstance;
}
// The interface:
virtual void foo() = 0;
virtual void bar() = 0;
};
And use that like
class DervivedA : public StaticInterface<DerivedA> {
template<typename Derived>
friend class StaticInterface<Derived>;
DerivedA() {}
public:
virtual void foo() {};
virtual void bar() {};
};
class DervivedB : public StaticInterface<DerivedB> {
template<typename Derived>
friend class StaticInterface<Derived>;
DerivedB() {}
public:
virtual void foo() {};
virtual void bar() {};
};
Or omit the virtual part (and creation of a "costly" vtable) completely:
template<typename Derived>
class StaticInterface {
protected:
StaticInterface() {}
public:
~StaticInterface() {}
static Derived& instance() {
Derived theInstance;
return theInstance;
}
// The interface:
void foo() {
Derived::foo_impl();
}
void bar() {
Derived::bar_impl();
}
};
class DervivedA : public StaticInterface<DerivedA> {
template<typename Derived>
friend class StaticInterface<Derived>;
DerivedA() {}
public:
void foo_impl() {};
void bar_impl() {};
};
I have a base class and a few derivative. I have to 'register' some static function from each of them. Here is the example:
class Base
{
// Some interface...
};
class Der1 : Base
{
static void Do();
};
class Der2 : Base
{
static void Do();
};
void processStatic()
{
SomeFunc(Der1::Do);
SomeFunc(Der2::Do);
}
As you see, SomeFunc receives function pointer. I want to do that automatically with each new derivative class, is it possible? Maybe, predefine static function in Base class and register it there. But I think it's impossible, yes?
Maybe, this will be more easier to understand what do I want:
class Der1 : Base
{
Der1() { SomeFunc(Der1::Do); }
static void Do();
};
class Der2 : Base
{
Der2() { SomeFunc(Der2::Do); }
static void Do();
};
EDIT: Completely replacing previous answer due to clarified requirements.
You could use the CRTP to declare a specialized base class that does nothing more than call your registration function:
#include <iostream>
void SomeFunc(void(*fp)()) {
(*fp)();
};
template <class D>
struct ExtraBass {
ExtraBass() {
static bool once;
if(!once)
SomeFunc(D::Do);
once = true;
}
};
struct Bass {
};
struct Drive : Bass, ExtraBass<Drive> {
static void Do() { std::cout << "Drive::Do\n"; }
};
struct Deride : Bass , ExtraBass<Deride> {
static void Do() { std::cout << "Deride::Do\n"; }
};
int main() {
Drive d1;
Deride d2;
Deride d3;
}
This is not an easy thing to do in C++, but I'm not saying it's impossible. If all you need is a list of subclass names, these answers might help:
Somehow register my classes in a list
c++ List of classes without initializing them for use of static functions
Seems either macro magic or boost mpl is your tool of choice.
I just wondering, if you did something like
void SomeFunc(void (*doFunc)())
{
doFunc();
}
template <class T> int Register()
{
SomeFunc(T::Do);
return 0;
}
template <class T> class Base
{
static int _i;
};
template <class T> int Base<T>::_i = Register<T>();
class Derived : Base<Derived>
{
public:
static void Do() { }
};