查找参数包的唯一值的数量 [英] Find number of unique values of a parameter pack

查看:165
本文介绍了查找参数包的唯一值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个带有可变参数的参数包,如何找到包中的唯一值的数量。我正在寻找

Given a parameter pack with variadic arguments, how can one find the number of unique values in the pack. I am looking for something along the lines of

no_of_uniques<0,1,2,1,2,2>::value // should return 3

我的基本实现看起来像这样

My rudimentary implementation looks something this

template <size_t ... all>
struct no_of_uniques;
// this specialisation exceeds -ftemplate-depth as it has no terminating condition
template <size_t one, size_t ... all>
struct no_of_uniques<one,all...> {
    static const size_t value = no_of_uniques<one,all...>::value;
};
template <size_t one, size_t two, size_t three>
struct no_of_uniques<one,two,three> {
    static const size_t value = (one==two && one==three && two==three) ? 1:
                                (one!=two && two==three) ? 2:
                                (one==two && one!=three) ? 2:
                                (one==three && two!=three) ? 2: 3;
};
template <size_t one, size_t two>
struct no_of_uniques<one,two> {
    static const size_t value = one==two ? 1: 2;
};
template <size_t one>
struct no_of_uniques<one> {
    static const size_t value = 1;
};

在这里,我专门为最多三个参数,但可以理解的是,代码随着参数数量呈指数增长。我想有一个 meta 解决方案,仅使用 STL ,没有第三方库如 Boost.MPL

Here, I have specialised for up to three arguments but understandably the code grows exponentially with the number of arguments. I would like to have a meta solution for this using solely STL and no third party libraries like Boost.MPL.

类似的问题虽然在检查唯一类型的上下文中,而不是查找参数包的唯一值的数量,可以在这里找到:

A similar question albeit in the context of checking unique types, rather than finding number of unique values of parameter pack can be found here:

检查可变参数模板参数的唯一性

在查找参数包的唯一值的数量的过程中,我们可能需要首先对包进行排序,并在其他问题中提供了一个很好的实现。

In the process of finding the number of unique values of a parameter pack, we might need to sort the pack first, and an excellent implementation of that is provided in this other question

使用C ++ 11变量在编译时快速排序模板

推荐答案

这里有一个简单的O(n ^ 2)方法。

Here's a simple O(n^2) way to do it

template <size_t...>
struct is_unique : std::integral_constant<bool, true> {};

template <size_t T, size_t U, size_t... VV>
struct is_unique<T, U, VV...> : std::integral_constant<bool, T != U && is_unique<T, VV...>::value> {};

template <size_t...>
struct no_unique : std::integral_constant<size_t, 0> {};

template <size_t T, size_t... UU>
struct no_unique<T, UU...> : std::integral_constant<size_t, is_unique<T, UU...>::value + no_unique<UU...>::value> {};

所以使用你的例子:

no_unique<0, 1, 2, 1, 2, 2>::value; // gives 3

这篇关于查找参数包的唯一值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆