如何创建一个概念来检查在C++中所有给定的类型参数是否不同?

huangapple go评论58阅读模式
英文:

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?

答案1

得分: 1

这是一个你可以使用的概念的示例:

#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); // 确实不会编译

    return 0;
}

注意:这只是提供了代码的翻译,没有其他额外的内容。

英文:

This an example of the concept you can use :

#include &lt;type_traits&gt;

template&lt;typename arg_t, typename... args_t&gt;
static consteval bool all_unique()
{
    if constexpr (sizeof...(args_t) == 0ul)
    {
        return true;
    }
    else
    {
        return (!std::is_same_v&lt;arg_t, args_t&gt; &amp;&amp; ...) &amp;&amp; all_unique&lt;args_t...&gt;();
    }
}

template&lt;typename... args_t&gt;
concept AllUnique = all_unique&lt;args_t...&gt;();

template&lt;typename...args_t&gt;
void f(args_t... args) requires AllUnique&lt;args_t...&gt;
{

}

int main()
{
    static_assert(all_unique&lt;int&gt;());
    static_assert(all_unique&lt;int,bool&gt;());
    static_assert(!all_unique&lt;int, bool, int&gt;());

    static_assert(AllUnique&lt;int&gt;);
    static_assert(AllUnique&lt;int, bool&gt;);
    static_assert(!AllUnique&lt;int, bool, int&gt;);

    f(1);
    f(1, true);
    // f(1, 2); // indeed does not compile
   
    
    return 0;
}

huangapple
  • 本文由 发表于 2023年5月30日 12:51:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定