【问题标题】:Forward-declare a class member typedef前向声明一个类成员 typedef
【发布时间】:2021-10-08 12:38:21
【问题描述】:

我的标题中有一个typedef,它是cl1 类的成员

template <size_t d>
class my_wkspc::cl1 {
  public:
    typedef std::vector<real> table_t;
    ...
    typename my_wkspc::cl2<d>& getCl2() { return _cl2; }  // <------ Not yet used
    ...
  private:
    typename my_wkspc::cl2<d>& _cl2;  // <------ Not yet used
};

我需要 typedef 作为类成员和类中的函数 cl2

namespace my_wkspc {
template <size_t d>
class cl2 {
  public:
    typename cl1<d>::table_t& getTable() const { return _table; }
    ...
  private:
    typename cl1<d>::table_t& _table;
    ...
};

现在我还需要定义cl2 类型的cl1 类成员(尚未实现)。 我认为我可以转发声明cl2,并将任何需要cl2 知识的cl1 成员函数放在源文件中(PS:这会破坏我的仅标题类)。
但是我可以将cl2 类定义放在cl1 之上,并带有某种typedef std::vector&lt;real&gt; table_t 的前向声明吗?

Forward declare typedef within C++ class 中,它被问到类似的问题(甚至更困难,与typedefs 的相互使用),但 OP 非常旧,并且答案(说明这是不可行的)可能会排除以后的替代方案。 一个后期模板实例化is suggested.

相关

  1. Forward-declare a typedef
  2. Forward declaring a typedef for a template class
  3. Forward declare a class's public typedef in c++
  4. Forward declaration of a forward-declared class member
  5. Forward declaration of a typedef in C++
  6. Forward declaring a template's member typedef

【问题讨论】:

  • 转发模板类,你可以这样做:template &lt;size_t&gt; class cl2;.
  • 问题是cl1cl2 之间的循环依赖。这是非常强的耦合,您有两种选择:中断循环,将两个类模板放在单个头文件中并与前向声明作斗争。
  • @Jarod42 - 我知道,这是我在 OP 中发布的一个选项的一部分(我将其称为一种解决方法)。

标签: c++ typedef forward-declaration


【解决方案1】:

创建一个定义table_t 的特征类,仅此而已。在两个地方都使用它。

转发声明模板。

template<std::size_t>class cl1;
template<std::size_t>class cl2;
template<std::size_t>struct table{
  using type=std::vector<real>;
};
template<std::size_t s>
using table_t=typename table<s>::type;

这假定ttable_t 实际上取决于模板参数。如果没有,就让它成为一个普通的 typedef/using 语句。

【讨论】:

  • 用一个单独的类替换类成员typedef(或者,在这种情况下,将新类添加到typedef/using)是一种选择。我的意思是避免它,但它在地图上。谢谢。
  • @sancho.s 你只能开一堂课。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 2016-06-19
  • 2018-11-02
  • 1970-01-01
相关资源
最近更新 更多