Search code examples
c++templatesc++14stdarraytemplate-argument-deduction

Cannot deduce template parameter 'N'


I tried to reduce this to its minimum:

#include <array>

template <std::size_t N>
void f(int, std::array<int, N> const & =
       std::array<int, 0>()) {
}


int main() {
    f(10);
}

array_test.cpp:4:6: note: template argument deduction/substitution failed: array_test.cpp:10:9: note: couldn't deduce template parameter ‘N’ f(10);

Why does this fail? I do not get it: it should be deducible from the default argument. I need a workaround.


Solution

  • You need to give a default value to N, not to the array:

    template <std::size_t N = 0>
    void f(int, std::array<int, N> const & =
           std::array<int, N>()) {
    
    }
    

    As to why the N cannot be deduced from the default value, see Why can't the compiler deduce the template type from default arguments?.