【问题标题】:Is this template syntax illegal?这个模板语法非法吗?
【发布时间】:2015-04-09 20:31:47
【问题描述】:

我在使用 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 ComparatorAndSorterTGeneralized.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

问题在于正在使用的模板&lt;typename U, U, U&gt; class Comparator。我以前从未尝试过。起初我尝试了模板&lt;typename T, T, T&gt; 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;
}

【问题讨论】:

  • “内部编译器错误”根据定义是编译器中的一个错误。无论您的问题的答案如何,请提交错误报告。
  • 在 clang++ 中编译,gcc4.9 和 gcc5 中的内部编译器错误
  • 致那些投反对票的人:无论他提交错误报告,问题仍然有效:如果它在 clang 或 VS 上编译,并不一定意味着语法按照标准是合法的。
  • @CássioRenan 正确,但它是带有“这有效吗?”的代码。添加到它的问题,没有任何理由为什么它可能有效或无效,或者为什么难以确定,或者非错误编译器对此有何评论(问题的初始版本)。这通常会被视为我缺乏足够的研究努力而投反对票。由于涉及 VS2015 预览行为的更新,我将避免投票,但我实际上仍然不认为这是一个很好的问题。
  • @hvd 是的,当然。你说的对。不过,也许 OP 根本没有方法或基本知识来知道从哪里开始寻找(我不会。要寻找什么?以该类型的类型和值作为参数的模板?不是一个友好的搜索问题引擎)。恕我直言,提供更多信息并不总是完全取决于努力。

标签: c++ templates


【解决方案1】:
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)是@987654332类型的非类型模板参数@。

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2014-08-18
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多