Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce type in function params and avoid implicit conversion?

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.

like image 317
joepol Avatar asked Dec 23 '22 16:12

joepol


1 Answers

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.

like image 164
Guillaume Racicot Avatar answered May 12 '23 12:05

Guillaume Racicot