Search code examples
c++inheritancetemplate-argument-deduction

deduction guide breaks for templated derived class


Here is minimal example:

#include <cstddef>
struct base_pod
{
};
template<typename T, std::size_t N>
struct der_pod : public base_pod
{
    T k[N];
};
template<typename T, typename... U>
    der_pod(T, U...)
        ->der_pod<std::enable_if_t<(std::is_same_v<T, U> and ...), T>, 1 + sizeof...(U)>;

int main()
{
    der_pod dp {{}, {3, 3} };
}

live demo

prog.cc:16:9: error: no viable constructor or deduction guide for deduction of template arguments of 'der_pod'
der_pod dp {{}, {3, 3} };
        ^
prog.cc:11:2: note: candidate template ignored: couldn't infer template argument 'T'
        der_pod(T, U...)
        ^
prog.cc:6:8: note: candidate function template not viable: requires 0 arguments, but 2 were provided
struct der_pod : public base_pod
       ^
prog.cc:6:8: note: candidate function template not viable: requires 1 argument, but 2 were provided
1 error generated.

I have to add explicit template argumentder_pod<int, 2> to pass compilation.

But deduction guide works fine when it has no base class:

template<typename T, std::size_t N>
struct der_pod
{
    T k[N];
};
template<typename T, typename... U>
    der_pod(T, U...)
        ->der_pod<std::enable_if_t<(std::is_same_v<T, U> and ...), T>, 1 + sizeof...(U)>;

int main()
{
    der_pod dp {3, 3};
}

live demo

1. What's behind?

2. How to fix


Solution

  • {}, {3, 3} have no type and don't allow deduction of T and U.

    Intead, you might use:

    template <typename T, std::size_t N>
    der_pod(base_pod, const T (&)[N]) -> der_pod<T, N>;
    

    Demo