jeudi 15 novembre 2018

CRTP applied on a template class

Let's consider a CRTP template class Print which is meant to print the derived class:

template <typename T>
struct Print {
    auto print() const -> void;
    auto self() const -> T {
        return static_cast<T const &>(*this);
    }

private:
    Print() {}
    ~Print() {}

    friend T;
};

Because I want to specialize print based on the derived class like we could do this with an override, I don't implement the method yet.

We can wrap an Integer and do so for example:

class Integer :
    public Print<Integer>
{
public:
    Integer(int i) : m_i(i) {}

private:
    int m_i;

    friend Print<Integer>;
};

template <>
auto Print<Integer>::print() const -> void {
    std::cout << self().m_i << std::endl;
}

This works so far, now let's say I want to Print a generic version of a wrapper:

template <typename T>
class Wrapper :
  public Print<Wrapper<T>>
{
public:
    Wrapper(T value) : m_value(std::move(value)) {}

private:
    T m_value;

    friend Print<Wrapper<T>>;
};

If I specialize my print method with a specialization of the Wrapper it compile and works:

template <>
auto Print<Wrapper<int>>::print() const -> void
{
  cout << self().m_value << endl;
}

But if I want to say "for all specializations of Wrapper, do that", it doesn't work:

template <typename T>
auto Print<Wrapper<T>>::print() const -> void
{
  cout << self().m_value << endl;
}

The compiler print:

50:42: error: invalid use of incomplete type 'struct Print<Wrapper<T> >'
6:8: error: declaration of 'struct Print<Wrapper<T> >'

Why ? How can I do that ? Is it even possible or do I have to make a complete specialization of my CRTP class ?

Aucun commentaire:

Enregistrer un commentaire