It's possible to give a templated constructor template parameters that cannot be deduced:
struct X
{
int i;
template<int N>
X() : i(N)
{
}
};
How would you use such a constructor? Can you use it at all?
It's possible to give a templated constructor template parameters that cannot be deduced:
struct X
{
int i;
template<int N>
X() : i(N)
{
}
};
How would you use such a constructor? Can you use it at all?
No, you can't specify constructor template arguments. There are a few alternatives.
std::integral_constant
parameter, which when passed as an argument, will deduce N
:Code:
#include <cassert>
#include <type_traits>
struct X
{
int i;
template<int N>
X(std::integral_constant<int, N>) : i(N)
{
}
};
int main()
{
std::integral_constant<int, 6> six;
X x(six);
assert(x.i == 6);
}
make_X<N>
template wrapper that hides the integral_constant
boiler-plate:Code:
template<int N>
X make_X()
{
return X(std::integral_constant<int, N>{});
}
int main()
{
auto y = make_X<42>();
assert(y.i == 42);
}