此模板语法是否非法

Is this template syntax illegal?

本文关键字:是否 非法 语法      更新时间:2023-10-16

我在使用 GCC 4.9.2 时遇到"内部编译器错误":

#include <type_traits>
template <typename T, typename, int, template <typename U, U, U> class>
struct Sort;
template <typename T, template <T...> class Z, T N, T... Is,
          template <typename U, U, U> class Comparator>
struct Sort<T, Z<N, Is...>, 0, Comparator> {
  template <T I>
  struct less_than : std::integral_constant<bool, Comparator<T, I, N>::value> {
  };
};
int main() {}

错误消息指出:

c:\ADandD>g++ -std=c++14 ComparatorAndSorterTGeneralized.cpp 比较器和排序器.cpp:254:80:内部编译器错误:在 tsubst, 在 CP/PT.C:11738

template<T I>
struct less_than : std::integral_constant<bool, Comparator<T,I,N>::value> {};
                                                                              ^

请提交完整的错误报告, 使用预处理的源(如果适用)。 有关说明,请参阅 http://gcc.gnu.org/bugs.html。

问题是正在使用的模板<typename U, U, U> class Comparator。我以前从未尝试过这个。起初我尝试了模板<typename T, T, T> class Comparator,但由于模板阴影而无法编译,所以我知道这是非法的。然后把它改成U仍然没有编译,所以我认为整个想法是不允许的。

更新:实例化后,这将在Visual Studio 2015 Preview中编译:

#include <type_traits>
template <typename T, typename, int, template <typename U, U, U> class>
struct Sort;
template <typename T, template <T...> class Z, T N, T... Is,
          template <typename U, U, U> class Comparator>
struct Sort<T, Z<N, Is...>, 0, Comparator> {
  template <T I>
  struct less_than : std::integral_constant<bool, Comparator<T, I, N>::value> {
  };
};
template <int...>
struct index_sequence {};
template <typename T, T A, T B>
    struct LessThan : std::integral_constant < bool,
    A<B> {};
enum { QuickSort, MergeSort, InsertionSort };
int main() {
  Sort<int, index_sequence<4, 5, 6, 1, 2, 7>, QuickSort, LessThan> quickSort;
}
template <typename T, typename, int, template <typename U, U, U> class>
  struct Sort;  

这是完全合法的。

它可以像这样重新声明,为所有参数命名:

template <typename T, typename T2, int I, template <typename U, U X, U Y> class TT>
  struct Sort;  

它声明了一个类模板Sort,该类模板具有四个模板参数,类型参数T,第二个类型参数T2(在原始中未命名),一个非类型模板参数I,以及一个模板模板参数TT

模板

模板参数TT必须是采用三个模板参数的类模板,U是类型参数,第二个和第三个(XY)是类型U的非类型模板参数。

Sort 的第四个模板参数的合适参数可能是这样的:

template <typename T, T t1, T t2>
  class Foo
  { static const bool value = t1 < t2; };

这将像这样实例化:

Foo<int, 1, 2> fi;

Foo<char, 'a', 'b'> fc;