gcc为什么会抱怨“错误:模板参数'0'的类型'intT'取决于模板参数”?

问题描述 投票:3回答:2

我的编译器是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
2个回答
8
投票

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

8在类模板部分专业化的参数列表中,存在以下限制:

  • 部分专用的非类型参数表达式不应包含的模板参数。部分特殊化,除非参数表达式是简单的identifier。 [Example:

    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

-结束示例

]] >>
  • ...

  • 我相信这里的第二点是最相关的。


    关于“如何解决此问题。恐怕问题就目前的形式来看,没有解决方法。

    至于具有整数序列的原始版本,我相信

    您可以使用uintmax_t作为非类型模板参数的类型,并仅将其转换为intT最终定义。

    直接使用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时...。


    0
    投票

    直接使用std :: integral_constant而不是整数常量:

    © www.soinside.com 2019 - 2024. All rights reserved.