mercredi 3 janvier 2018

Using CRTP with public interface

I'm currently using CRTP with a public interface to implement multiple inheritance at compile time while having a public interface that I can use to store my objects into containers. Here's a simple example: http://ift.tt/2lQ13US

#include <iostream>
#include <memory>

struct interface {
    virtual void foo() noexcept = 0;
};

template <typename T>
struct crtp : public interface {
    void foo() noexcept override {
        static_cast<T *>(this)->do_foo();
    }
};

struct imp1 : public crtp<imp1> {
    void do_foo() noexcept {
        std::cerr << "foo 1!" << std::endl;
    }
};

struct imp2 : public crtp<imp2> {
    void do_foo() noexcept {
        std::cerr << "foo 2!" << std::endl;
    }
};

int main() {
    std::unique_ptr<interface> aaa(new imp1);
    std::unique_ptr<interface> bbb(new imp2);

    aaa->foo();
    bbb->foo();
}

Using the latest Clang in the latest OSX I get a number of warnings in the constructor of the implementation classes, one line per method in the public interface:

Instantiation of function '' required here, but no definition is available

Is there a way to tell the compiler that everything is fine and the implementation is taken care of via CRTP?

Aucun commentaire:

Enregistrer un commentaire