尝试从模板类型列表中删除相邻重复项时出现编译错误

Compilation error when trying to remove adjacent duplicates from a template typelist

我想要达到的结果是:

removeduplicates<TMPArray<8, 8, 9, 9, 10, 11, 11>>::type 结果与 TMPArray<8, 9, 10, 11>

的类型相同

到目前为止,我的解决方案如下所示:


template<int... I>
struct TMPArray {};

template <typename Arr1, typename Arr2>
struct concat;

template <int Ts, int... Us>
struct concat<TMPArray<Ts>, TMPArray<Us...>>
{
    using type = TMPArray<Ts, Us...>; 
};

template <int... Ts, int... Us>
struct concat<TMPArray<Ts...>, TMPArray<Us...>>
{
    using type = TMPArray<Ts..., Us...>;
};

template<typename TMPArray>
struct removeduplicates;

template<bool isSame, typename TMPArray>
struct makeremoveduplicates;

template<int Head, int Sec, int... Tail>
struct removeduplicates<TMPArray<Head, Sec, Tail...>> {
    using type = makeremoveduplicates<Head == Sec, TMPArray<Head, Sec, Tail...>>;
};

template<int Head, int Sec, int Third, int... Tail>
struct makeremoveduplicates<false, TMPArray<Head, Sec, Third, Tail...>> {
    using type = concat<TMPArray<Head>,makeremoveduplicates<Sec == Third,TMPArray<Sec, Third, Tail... >>::type>::type;
};

template<int Head, int Sec, int Third, int... Tail>
struct makeremoveduplicates<true, TMPArray<Head, Sec, Third, Tail...>> {
    using type = makeremoveduplicates<Sec == Third, TMPArray<Sec, Third, Tail... >>::type;
};

template<int Head, int Sec>
struct makeremoveduplicates<true, TMPArray<Head, Sec>> {
    using type = TMPArray<Head>;
};
 
template<int Head, int Sec>
struct makeremoveduplicates<false, TMPArray<Head, Sec>> {
    using type = TMPArray<Head, Sec>;
};

这个解决方案背后的想法是,我使用助手 makeremoveduplicates 来比较前两个元素,并在它们匹配或不匹配时调用专门的模板。这将使用 concat 元函数递归地附加结果。

我遇到一个编译错误,指出:

Error   C2923   'concat': 'makeremoveduplicates<Sec==Third,TMPArray<Sec,Third,Tail...>>::type' is not a valid template type argument for parameter 'Arr2'

我希望 makeremoveduplicates 类型根据基本情况评估为 TMPArray:

template<int Head, int Sec>
struct makeremoveduplicates<true/false, TMPArray<Head, Sec>>

和concat的结果:

template <int Ts, int... Us>
struct concat<TMPArray<Ts>, TMPArray<Us...>>
{
    using type = TMPArray<Ts, Us...>; 
};

为什么这不是有效类型?

我看到的问题是,在你的代码的三个点中,你必须添加一个 typename 来说明编译器接下来是 typename.

我希望this answer能解释为什么。

你必须在这里添加两个typename

template<int Head, int Sec, int Third, int... Tail>
struct makeremoveduplicates<false, TMPArray<Head, Sec, Third, Tail...>> {
    // ..........VVVVVVVV........................VVVVVVVV
    using type = typename concat<TMPArray<Head>, typename makeremoveduplicates<Sec == Third,TMPArray<Sec, Third, Tail... >>::type>::type;
};

这里还有一个

template<int Head, int Sec, int Third, int... Tail>
struct makeremoveduplicates<true, TMPArray<Head, Sec, Third, Tail...>> {
    // ..........VVVVVVVV
    using type = typename makeremoveduplicates<Sec == Third, TMPArray<Sec, Third, Tail... >>::type;
};