Search code examples
c++templatesvariadic-templatesc++-concepts

How to create a concept to check if all the given type parameters are different in C++?


A concept which checks if the first given type parameter is different from the rest of type parameters is as following:

template<typename TYPE, typename ... TYPES>
concept different = ((not std::same_as<TYPE, TYPES>) and ...);

(std::same_as is from <concepts> standard library)

But how to check if all the given type parameters are different from each other?


Solution

  • This an example of the concept you can use :

    #include <type_traits>
    
    template<typename arg_t, typename... args_t>
    static consteval bool all_unique()
    {
        if constexpr (sizeof...(args_t) == 0ul)
        {
            return true;
        }
        else
        {
            return (!std::is_same_v<arg_t, args_t> && ...) && all_unique<args_t...>();
        }
    }
    
    template<typename... args_t>
    concept AllUnique = all_unique<args_t...>();
    
    template<typename...args_t>
    void f(args_t... args) requires AllUnique<args_t...>
    {
    
    }
    
    int main()
    {
        static_assert(all_unique<int>());
        static_assert(all_unique<int,bool>());
        static_assert(!all_unique<int, bool, int>());
    
        static_assert(AllUnique<int>);
        static_assert(AllUnique<int, bool>);
        static_assert(!AllUnique<int, bool, int>);
    
        f(1);
        f(1, true);
        // f(1, 2); // indeed does not compile
       
        
        return 0;
    }