Search code examples
c++templatesimplicit-conversion

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.


Solution

  • You could add a second template parameter and a static_assert in the function to make sure that second parameter is exactly of the same type as the container's value type.

    template<typename T, typename U>
    static inline bool Contains(const T& container, const U& value)
    {   
        static_assert(std::is_same_v<typename T::value_type, U>, "NO IMPLICIT CONVERSION ALLOWED");
        return std::find(container.begin(), container.end(), value) != container.end();
    }
    
    int main() {
        std::vector<int> vec = {1, 2, 3};
        Contains(vec, -5.2);  // Fails now
    }
    

    Full example here.