对于固定数量的模板参数,虽然手动编写的检查数量呈二次方增长,但这很容易。
#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;
}
如何为具有任意数量类型的参数包实现这一点?
答案 0 :(得分:4)
你可以这样做:
#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;
}