首页 > 解决方案 > 用另一个类模板实例化一个类模板会导致使用不完整的类型

问题描述

假设我们有以下类模板:

template<size_t S>
struct A
{
  char str[S];
};

template<typename T>
class B
{
  T t;

public:
  void init(); // Should initialize the 't' member in some a way.
};

现在,如果我专门init用一些非模板类型作为模板的参数B,就可以了。但是,如果不指定它的值,我不能将它A作为参数专门化。即,我想做这样的事情:BS

template<>
void B<A<S>>::init()
{
  // Initialize the 't.str'. For example:
  memset(t.str, 0, S);
}

标签: c++templates

解决方案


要提供执行特定于 的部分特B<A<???>>化,您实际上需要为类提供这样的部分特化:

#include <cstddef>
#include <cstring>
#include <iostream>

template<std::size_t S>
struct A
{
  char str[S];
};

template<typename T>
class B
{
  T t;

public:
  void init(); // Should initialize the 't' member in some a way.
};

template<std::size_t S>
class B<A<S>> {
  using T = A<S>;

  T t;

public:
  void init(); // Should initialize the 't' member in some a way.
};

template<std::size_t S>
void B<A<S>>::init()
{
  // Initialize the 't.str'. For example:
  std::memset(t.str, 0, S);
  std::cout << "Initialized B<A<" << S << ">>\n";
}

int main() {
    B<A<3>> b;
    b.init();
}

请注意,您的代码有两个主要区别:

  1. 类模板有部分特化template<std::size_t S> class B<A<S>>
  2. 该类模板的init成员函数现在可以定义为template<std::size_t> void B<A<S>>::init() { /* ... */ }

如果在您的用例中没有其他实例有效,您可以省略类模板的基本案例定义B并将其替换为。template<typename T> class B;

现场观看


推荐阅读