Why the following class A
can't deduce its template parameters in the code below:
#include <functional>
template <class... Ts>
class A
{
public:
using Func = std::function<void(std::decay_t<Ts>...)>;
A(Func func) : m_func(func)
{
}
private:
Func m_func;
};
int main()
{
//compiles
A<int, bool> a([](int, bool) {});
//does not compile with error 'class template argument deduction failed'
A b([](int, bool) {});
return 0;
}
The class have a data member of type Func
and needs to know the types of its parameters. How to make it compile?
EDIT1:
I was able to make this compile with std::tuple
:
#include <tuple>
template <class... Ts>
class A
{
public:
using Func = std::tuple<Ts...>;
constexpr A(Func func) : m_func(func)
{
}
private:
Func m_func;
};
int main()
{
std::tuple<int, bool> t;
//compiles
A<int, bool> a(t);
//do not compile with error 'class template argument deduction failed'
A b(t);
return 0;
}
std::decay_t
results in the type used in the template instantiation. That's not deducible. And since a lambda is just an anonymous class, there is no way to deduce something like that, either.std::function
's deduction guide could get somewherestd::tuple
is better thanstd::function
, see EDIT1, removingstd::decay_t
does not help.std::function
from a lambda has been re-hashed already on SO. For example stackoverflow.com/questions/53326206/…