如何检查参数包中的每种类型是否唯一? [英] How to check if every type in a parameter pack is unique?
本文介绍了如何检查参数包中的每种类型是否唯一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于固定数量的模板参数,这很容易,尽管手动编写的检查的数量呈二次增长。
For a fixed number of template parameters it is easy, although the number of manually written checks grows quadratically.
#include <type_traits>
template <
typename T1,
typename T2,
typename T3,
typename T4>
struct unique_types
{
static_assert(!std::is_same<T1, T2>::value, "Types must be unique");
static_assert(!std::is_same<T1, T3>::value, "Types must be unique");
static_assert(!std::is_same<T1, T4>::value, "Types must be unique");
static_assert(!std::is_same<T2, T3>::value, "Types must be unique");
static_assert(!std::is_same<T2, T4>::value, "Types must be unique");
static_assert(!std::is_same<T3, T4>::value, "Types must be unique");
};
int main()
{
// OK.
unique_types<int, double, char, float> foo;
// Should not compile.
unique_types<int, double, char, double> bar;
}
对于具有任意数量类型的参数包如何实现?
How could this be implemented for a parameter pack with an arbitrary number of types?
推荐答案
您可以这样做:
#include <type_traits>
template <class ... Trest>
struct unique_types;
template <class T1, class T2, class ... Trest>
struct unique_types<T1, T2, Trest ...>
: unique_types<T1, T2>, unique_types<T1, Trest ...>, unique_types<T2, Trest ...> {};
template <class T1, class T2>
struct unique_types<T1, T2>
{
static_assert(!std::is_same<T1, T2>::value, "Types must be unique");
};
int main()
{
// OK.
unique_types<int, double, char, float> foo;
// Should not compile.
unique_types<int, double, char, double> bar;
}
这篇关于如何检查参数包中的每种类型是否唯一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文