CRTP compiles, but I'd like it not to. How? - c++

I have this CRTP with an incomplete child class that is missing a method that is "not really" implemented in the base class:
#include <iostream>
using namespace std;
template<class T>
class BaseA
{
public:
T& asChild(){return static_cast<T&>(*this);}
void AMethod(void) {asChild().AMethod();}
};
class IncompleteChild : public BaseA<IncompleteChild>
{
public:
// uncomment the following to avoid segfault:
// void AMethod(void) {cout << "IncompleteChild Method" << endl;}
};
class Child : public BaseA<Child>
{
public:
void AMethod(void) {cout << "Child AMethod" << endl;}
};
template<class T>
void printBaseA(BaseA<T>& a)
{
a.AMethod();
}
int main()
{
IncompleteChild cI;
cI.AMethod();
printBaseA(cI);
return 0;
}
This compiles fine, but results in a segmentation fault at runtime. How can I avoid that? I'd prefer a compiler error here (using gcc 4.6.3).

Since your class doesn't actually have a member AMethod, you end up calling the member of the CRTP base, which gives you infinite recursion.
The simple solution is not to reuse names all over the place, but have one called AMethod and the other AMethodImpl or something like that:
void AMethod()
{
static_cast<T*>(this)->AMethodImpl();
}

Related

How to avoid paying for interface virtual methods during inversion of control in C++?

I work on this C++ code base which has a great architecture, very decoupled and easy to test. Though one thing that really bothers me is paying for virtual methods when most of times it isn't actually needed because the correct derived class is chosen once, during dependecy injection and dynamic polymorphism isn't needed. For example:
#include <iostream>
#include <memory>
class IDog{
public:
virtual void bark() = 0;
~IDog() = default;
};
class Dog : public IDog {
public:
void bark() override {std::cout << "woof" << std::endl;}
};
void makeDogSound(std::unique_ptr<IDog> dog){
dog->bark();
}
//prod main
int main(){
makeDogSound(std::make_unique<Dog>());
}
//test
class MockDock : public IDog {
public:
void bark() override {std::cout << "mock woof" << std::endl;}
};
//test main
int main(){
makeDogSound(std::make_unique<MockDock>());
}
I looked at some template based approachs like this one below:
#include <iostream>
#include <memory>
class Dog{
public:
void bark() {std::cout << "woof" << std::endl;}
};
template<typename DogT>
void makeDogSound(std::unique_ptr<DogT> dog){
dog->bark();
}
//prod main
int main(){
makeDogSound(std::make_unique<Dog>());
}
//test
class MockDock{
public:
void bark() {std::cout << "mock woof" << std::endl;}
};
//test main
int main(){
makeDogSound(std::make_unique<MockDock>());
}
But it seems that:
It would be difficult to keep track of the "dog interface" signature because they would be generated on the fly, every time I call a dog method inside makeDogSound.
Autocomplete wouldn't work inside makeDogSound as it doesn't know about the Dog avaiable methods.
I don't rule out that maybe I'm not understanding well the template based approach.
It also seems to me that using C++20 concepts could be a way to ensure a strong interface at compile time.
You're right that a C++20 concept would work well here to describe the interface:
template <typename Dog>
concept doglike = requires(Dog dog) {
{ dog.bark(); };
{ dog.name(); } -> std::convertible_to<std::string>; // example of how to specify return type, use std::same_as if you don't want conversions.
}
You could then write
template <doglike DogT>
void makeDogSound(std::unique_ptr<DogT> dog){
dog->bark();
}
and if you try calling this function template with an object that isn't doglike, you'll get a clear compiler error telling you so.

How to declare a template method of a template base class using 'using'?

Two methods for accessing template base class members are described here. When the base class member itself is a template, accessing it using the first method (this->) above is described here. Is there a way to use the second method (using xxxx) in this scenario as well?
For example, in the code below, is it possible to replace "????" with something to make the code work?
using namespace std;
template<typename T> class base
{
public:
template<bool good> void foo()
{
cout << "base::foo<" << boolalpha << good << ">()" << endl;
}
};
template<typename T> class derived : public base<T>
{
public:
using ????
void bar()
{
foo<true>();
}
};
Just for the record, even though it does not provide any answer or workaround, but I am currently working with VS Express 2013, and I can assure you that
#include <iostream>
template<typename T> class base
{
public:
template<bool good> void foo()
{
std::cout << "base::foo<" << good << ">()" << std::endl;
}
};
template<typename T> class derived : public base<T>
{
public:
void bar()
{
foo<true>();
}
};
struct A{};
void main() {
derived<A> a;
a.bar();
}
works perfectly fine...

C++ calling a inherited method of a templated superclass

I don't understand why the following code does not compile:
#include <iostream>
using namespace std;
template<typename T>
class Base {
public:
void printTuple(T tuple) {
std::cout << "Hello1!" << std::endl;
}
};
template<typename T>
class Derived : public Base<T> {
public:
void printTuple(std::string name, T tuple) {
std::cout << "Hello2!" << std::endl;
printTuple(tuple);
}
};
int main()
{
Derived<int> d1;
d1.printTuple("Test", 13);
return 0;
}
I get the following error:
main.cpp:19:25: error: no matching function for call to Derived::printTuple(int&)'
But shouldn't Derived inherit a method with such a signature from Base?
Thanks
You should change the line printTuple(tuple) to Base<T>::printTuple(tuple) because a function of the base class has been hidden.
Just add this to the top of the public part of class Derived:
using Base<T>::printTuple;
This will expose the base class overload of the function, i.e. prevent it from being "shadowed."

C++ multiple inheritance static function call ambiguity

I have the case where I am deriving a class from two different base classes both having a static function with the same name.
To resolve this ambiguity, I tried to use the scope operator - just as I would do for a member function. However This does not compile. Why? Wrong syntax?
I want to call the static function via the derived typename and not directly via base class name. Actually I would like prefer to prevent this case, but I have no idea how to do so.
The error (commented out) in the code below also occurs, when I leave the templates away:
#include <iostream>
template<class TDerived>
class StaticBaseA
{
public:
static void announce()
{
std::cout << "do something" << std::endl;
}
};
template<class TDerived>
class StaticBaseB
{
public:
static void announce()
{
std::cout << "do something else" << std::endl;
}
};
class Derived :
public StaticBaseA<Derived>
, public StaticBaseB<Derived>
{
using StaticBaseA<Derived>::announce;
};
class NonDerived {};
int main(int argc, char* argv[])
{
Derived::announce();
// What I want:
//Derived::StaticBaseB<Derived>::announce(); Error: "Undefined symbol 'StaticBaseB'
// What works, but what I don't want ...
StaticBaseB<Derived>::announce();
// ... because I would like to prevent this (however this is done):
StaticBaseB<NonDerived>::announce();
return 0;
}
Making "announce" protected in StaticBaseA and StaticBaseB might be part-way to doing what you want.
You then could not call StaticBaseB<NonDerived>::announce from main as it would be inaccessible. You could call it from a class derived from StaticBaseB.
In other words:
template<class TDerived>
class StaticBaseA
{
protected:
static void announce()
{
std::cout << "do something" << std::endl;
}
};
template<class TDerived>
class StaticBaseB
{
protected:
static void announce()
{
std::cout << "do something else" << std::endl;
}
};
In Derived you have to promote "announce" to public.
class Derived : public StaticA<Derived>, public StaticB<Derived >
{
public:
using StaticA<Derived>::announce;
};
int main()
{
Derived::announce(); // legal and calls StaticBaseA::announce
NotDerived::announce(); // no such function
StaticBaseA< Derived >::announce(); // not accessible
StaticBaseB< Derived >::announce(); // also not accessible
StaticBaseA< NotDerived >::announce(); // not accessible
StaticBaseB< NotDerived >::announce(); // also not accessible
}

C++: Require static function in abstract class

I am trying to write a c++ abstract class and I can't figure out how to require implementers of this class to contain a static function.
For example:
class AbstractCoolThingDoer
{
void dosomethingcool() = 0; // now if you implement this class
// you better do this
}
class CoolThingDoerUsingAlgorithmA: public AbstractCoolthingDoer
{
void dosomethingcool()
{
//do something cool using Algorithm A
}
}
class CoolThingDoerUsingAlgorithmB: public AbstractCoolthingDoer
{
void dosomethingcool()
{
//do the same thing using Algorithm B
}
}
Now I'd like to do the coolthing without the details of how coolthing gets done. So I'd like to do something like
AbstractCoolThingDoer:dosomethingcool();
without needing to know how the coolthing gets done, but this seems to require a function that is both virtual and static which is of course a contradiction.
The rationale is that CoolThingDoerUsingAlgorithmB may be written later and hopefully the softare that needs cool things done won't have to be rewritten.
EDIT:Not sure I was clear on what I'm trying to accomplish. I have 3 criteria that I'm looking to satisfy
A library that uses abstractcoolthingdoer and does not need to be rewritten ever, even when another coolthingdoer is written that the library has never heard of.
If you try to write a coolthingdoer that doesn't conform to the required structure, then the executable that uses the library won't compile.
coolthingdoer has some static functions that are required.
I'm probably chasing down a poor design, so please point me to a better one. Am I needing a factory?
Maybe, something like this will help (see ideone.com example):
#include <iostream>
class A
{
protected:
virtual void do_thing_impl() = 0;
public:
virtual ~A(){}
static void do_thing(A * _ptr){ _ptr->do_thing_impl(); }
};
class B : public A
{
protected:
void do_thing_impl(){ std::cout << "B impl" << std::endl; }
};
class C : public A
{
protected:
void do_thing_impl(){ std::cout << "C impl" << std::endl; }
};
int main()
{
B b_;
C c_;
A::do_thing(&b_);
A::do_thing(&c_);
return (0);
}
EDIT: It seems to me the OP does not need run-time polymorphism, but rather compile-time polymorphism without need of class instance (use of static functions when the implementation is hidden in the derived classes, no instance required). Hope the code below helps to solve it (example on ideone.com):
#include <iostream>
template <typename Derived>
struct A
{
static void do_thing() { Derived::do_thing(); }
};
struct B : public A<B>
{
friend A<B>;
protected:
static void do_thing() { std::cout << "B impl" << std::endl; }
};
struct C : public A<C>
{
friend A<C>;
protected:
static void do_thing() { std::cout << "C impl" << std::endl; }
};
int main()
{
A<B>::do_thing();
A<C>::do_thing();
return (0);
}
EDIT #2: To force fail at compile-time in case user does not adhere to desired pattern, here is the slight modification at ideone.com:
#include <iostream>
template <typename Derived>
struct A
{
static void do_thing() { Derived::do_thing_impl(); }
};
struct B : public A<B>
{
friend A<B>;
protected:
static void do_thing_impl() { std::cout << "B impl" << std::endl; }
};
struct C : public A<C>
{
friend A<C>;
protected:
static void do_thing_impl() { std::cout << "C impl" << std::endl; }
};
struct D : public A<D>
{
friend A<D>;
};
int main()
{
A<B>::do_thing();
A<C>::do_thing();
A<D>::do_thing(); // This will not compile.
return (0);
}
This looks to me like right place to implement bridge pattern. Maybe this is what you are (unconsciously) willing to achieve. In short you specify an interface and its implementations, then call to your do_thing method in turn calls an implementation on a pointer to implementer class.
C++ example