c++ - 模板特化的不正确实例化

标签 c++ template-specialization

在下面的代码中,我尝试特化类 A对于模板参数 T 时的基本情况具有值(value) B<m> .

#include <array>
#include <iostream>

template <std::size_t m>
struct B
{
  std::array<double,m> arr;
};


template <std::size_t n, typename T>
struct A
{
  std::array<T,n> arr;
  const static int inner_dim = T::inner_dim;
};

template <std::size_t n >
template <std::size_t m>
struct A<n,B<m>>
{
  std::array<B<m>,n> arr;
  const static int inner_dim = m;
};


int main(int argc, char *argv[])
{
  A<5,A<4,B<3>>> a;
  std::cout << a.inner_dim << std::endl;

  A<5,B<4>> b;
  std::cout << b.inner_dim << std::endl;

  return 0;
}

但是,在 main 中的实例化中,当我使用 g++ 5.4 编译时出现以下错误:

$ g++ -Wall --std=c++11 specialization.cc 
specialization.cc: In instantiation of ‘const int A<4ul, B<3ul> >::inner_dim’:
specialization.cc:15:20:   required from ‘const int A<5ul, A<4ul, B<3ul> > >::inner_dim’
specialization.cc:30:18:   required from here
specialization.cc:15:20: error: ‘inner_dim’ is not a member of ‘B<3ul>’
   const static int inner_dim = T::inner_dim;
                    ^
specialization.cc: In instantiation of ‘const int A<5ul, B<4ul> >::inner_dim’:
specialization.cc:33:18:   required from here
specialization.cc:15:20: error: ‘inner_dim’ is not a member of ‘B<4ul>’

似乎只使用了一般定义,从未使用过特化。如何确保实例化正确的特化?

最佳答案

我的猜测是

template <std::size_t n >
template <std::size_t m>
struct A<n,B<m>>

应该是

template <std::size_t n, std::size_t m>
struct A<n,B<m>>

关于c++ - 模板特化的不正确实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087372/

相关文章:

C++删除二叉树中的最小元素

C++ 模板递归检查 std::tuple 中的类型

c++ - 这个构造函数做什么?

c++ - 使用 OpenGL 着色器在 C++ 中以 2D 形式绘制 4D 点

c++ - ToString<T> 好的做法?

c++ - 在派生类中执行成员模板类的部分类内特化是否合法

c++ - 用于初始化模板类的静态数据成员的部分模板特化

c++ - 关于调用具有专门模板的类的混淆

c++ - SDL2 pollevent() Controller d'pad 连续保持?

c++ - 具有完全专用别名的实现切换