【问题标题】:Can we not declare template members inside c++?我们不能在 C++ 中声明模板成员吗?
【发布时间】:2020-07-22 19:39:33
【问题描述】:

看下面的情况: 我想让指针声明通用,但它抛出错误:成员'b_pointer'声明为模板。有什么办法可以实现吗?

class A {

protected: 
template<class x> x *b_pointer;          //this throws an error
B *b_pointer;                            //this does not throw an error
{;



【问题讨论】:

  • “使指针声明通用”对您意味着什么?
  • 要求人们阅读您有缺陷的代码并了解您的意图通常并不比要求您的编译器阅读您的有缺陷的代码并生成您想要的可执行文件更成功。请尽量用文字描述您的情况。代码应仅用作备用说明,而不是主要的交流方式。

标签: c++ templates compiler-errors


【解决方案1】:

改为声明一个模板类

template<class T>
class A {
    T* p;
};

【讨论】:

  • 但这不能在课堂内完成吗?除了模板化整个班级之外,没有其他方法可以做到这一点吗?
  • 没办法。但是,您可以声明一个静态模板成员变量。在您的问题下查看 Mikel 的评论。@Mandar
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 2011-01-30
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多