I was trying to simplify a template function by using a template alias instead of the underlying type:
template<typename T,
typename Traits = std::char_traits<T>,
typename Allocator = std::allocator<T>,
typename String = std::basic_string<T, Traits, Allocator>,
typename Vector = std::vector<String>>
Vector make_vector_from_string(const String & str)
{
//do something with str parameter
return Vector{
{str}
};
}
But the caller is required to specify the template type because the compiler fails to deduce T for the parameter:
std::string bar{"bar"};
auto strings{make_vector_from_string<char>(bar)};
If the function parameter type is changed to std::basic_string<T, Traits, Allocator>
instead of String
the caller can simply call make_vector_from_string(bar);
without having to specify the template parameter. Why is that?
T
is non deducible, only String
is.
If you want to provide type automatically for T
, Traits
, Allocator
. You have to do it the other way:
template <
typename String,
typename T = typename String::value_type,
typename Traits = typename String::traits_type,
typename Allocator = typename String::allocator_type,
typename Vector = std::vector<String>>
Vector make_vector_from_string(const String& str)
{
//do something with str parameter
return {str};
}
But
template <typename String>
std::vector<String> make_vector_from_string(const String& str)
{
//do something with str parameter
return {str};
}
Seems enough.
Or even
std::vector<std::string> make_vector_from_string(const std::string& str)
{
return { str};
}