I have a function
template<typename T>
static inline bool Contains(T container, const typename T::value_type& value)
{
return std::find(container.begin(), container.end(), value) != container.end();
}
Is there an option to disallow implicit conversions for this function?
This code should fail compilation:
std::vector<int> vec = {1, 2, 3};
Contains(vec, -5.2);
In this post How do I avoid implicit conversions on non-constructing functions? they totally remove the use of some types, which is not the case.
Thanks.
In C++20, it would be as simple as this:
template<typename T>
static inline bool Contains(T container, std::same_as<typename T::value_type> auto const& value)
{
return std::find(container.begin(), container.end(), value) != container.end();
}
In this code std::same_as
is a concept, and can be used with the terse template syntax.
One advantage with this solution is that the compiler error happen at the call site, telling the user that the type of the parameter is wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With