【问题标题】:Why does gcc complain "error: type 'intT' of template argument '0' depends on a template parameter"?为什么 gcc 会抱怨“错误:模板参数'0'的类型'intT'取决于模板参数”?
【发布时间】:2014-08-30 15:04:49
【问题描述】:

我的编译器是 gcc 4.9.0。以下代码无法编译:

template<typename T, T i>
struct value {};

template<typename T>
struct value<T, 0> {};
// error: type 'T' of template argument '0' depends on a template parameter

原因是什么?以及,如何解决这个问题?

【问题讨论】:

标签: c++ templates c++11 variadic-templates template-meta-programming


【解决方案1】:

GCC 是对的,这是 C++11 [temp.class.spec] §8 明确禁止的:

8 在类模板部分特化的参数列表中,适用以下限制:

  • 部分特化的非类型实参表达式不应包含 部分特化,除非参数表达式是一个简单的标识符。 [示例:

    template <int I, int J> struct A {};
    template <int I> struct A<I+5, I*2> {}; // error
    template <int I, int J> struct B {};
    template <int I> struct B<I, I> {}; // OK
    

    ——结束示例 ]

  • 对应于专门的非类型实参的模板形参的类型不应是 取决于专业化的参数。 [ 例子:

    template <class T, T t> struct C {};
    template <class T> struct C<T, 1>; // error
    template< int X, int (*array_ptr)[X] > class A {};
    int array[5];
    template< int X > class A<X,&array> { }; // error
    

    ——结束示例 ]

  • ...

我认为第 2 点是最相关的。


关于“如何解决这个问题”的问题。就目前的问题而言,恐怕没有解决方法。

至于制作整数序列的原始版本,我相信您可以使用uintmax_t 作为非类型模板参数的类型,并且只将其转换为@ 987654325@在最终定义中。

【讨论】:

  • 解决方案在哪里?
  • @Angew:天哪,我为此奋斗过,它真的很顽固……很高兴你成功了!
  • @xmllmx 您问的是为什么它不起作用,而不是如何使它起作用。您的问题的缩短版本有一个简单的答案“这行不通”。不过,原来的可能有不同的解决方案。不过,问题是“为什么?”
  • @MatthieuM。我有时会忘记标准 PDF 的副本看起来未经编辑有多糟糕。
  • @xmllmx:我猜该解决方案涉及不使用部分专业化。你真的需要你提到的那些整数序列吗?它们已经存在于 C++14 (see here) 中。
【解决方案2】:

直接使用 std::integral_constant 代替整数文字:

template<typename T, typename VALUE>
struct value;

template<typename T>
struct value<T, std::integral_constant<T, 0> >
{
};

当我尝试为 C++11 实现 std::make_integer_sequence 时,这对我来说很好......

【讨论】:

    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 2012-07-02
    • 2015-10-08
    • 2017-08-30
    • 2022-01-09
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多