如何避免使用CRTP奇怪的重复模板模式来实现功能共享

时间:2018-08-28 12:17:52

标签: c++ crtp

我继承了使用CRTP(Curiously recurring template pattern)的绘图程序的维护 以便在不同维度的类之间共享派生函数。

尽管使用derived().my_funct()可以在所有编译器上使用,但它会混淆Visual Studio的智能感知和调试以及Doxygen,因此我希望以后不再使用它。

下面的骨架程序说明了我想做什么。

问题的核心是数百个小功能,这些功能可以设置所有维度通用的功能-引用svg1&svg2除外,以允许与return *this链接。

>

我可以创建两个包含文件,它们的区别仅在于svg&,但这是不雅观的,也是维护的噩梦。

建议。

//svg2.hpp

  #include <string>

  class svg1;
  class svg2;

  class svg1
  {
  public:
    static const int dim_ = 1;
    int size_ = 0;
    std::string title_;
    svg1(std::string title = "title")
    {
      title_ = title;
    }

    svg1& size(int s)   // Note svg1&
    {
      size_ = s;
      return *this; // Chainable.
    }

    // There are nearly 300 more chainable functions like size.

  }; // class svg1

  class svg2
  {
  public:
    static const int dim_ = 2;
    int size_ = 0;
    std::string title_;
    svg2(std::string title = "title")
    {
      title_ = title;
    }

    svg2& size(int s)   // Note svg2&, otherwise identical, so want to avoid duplicating hundreds of functions!
    {
      size_ = s;
      return *this; // Chainable.
    }
  }; // class svg2



  #include <string>

  #include "svg2.hpp"

  int main()
  {
    svg1 plot1("my_1D_title");
    plot1.size(99);

    svg2 plot2("my_2D_title");
    plot2.size(99);

    return 0;
  }

0 个答案:

没有答案