【问题标题】:CRTP and method returning void *CRTP 和方法返回 void *
【发布时间】:2016-06-02 03:07:45
【问题描述】:

我使用 C++ 11。我有一个 Base 类和几个派生类,用于逐行解析不同的配置文件。

template <class T>
class Base
{
public:
    virtual ~Base();
    bool load_from_file(const QString& str);
    virtual void* get_data(const QString& str) const  = 0;

private:
    QList<QSharedPointer<T> > items_;
};

每个后代 (class Derived: public Base&lt;My_struct&gt;) 必须提供 get_data() 实现。
每个My_struct 实例都包含来自设置文件某行的信息。

例如,想象一个带有代理列表的典型文件。
My_struct 实例在load_from_file() 方法的Base 类中被包装在智能指针中,并附加到items_ 成员。 load_from_file() 方法在包装之前将 void* 强制转换为 T*

是否可以重新设计这些类以避免使用void*(并且没有像boost::any 这样的库)?
我的意思是考虑 CRTP 等等。通常 CRTP 示例包含具有 void 返回值的派生类的方法(如 Pascal 中的过程)。

【问题讨论】:

  • 您真正希望get_data 返回什么类型? My_struct?
  • CRTP 是 class Derived: public Base&lt;Derived&gt;,而不是其他结构。然后你可以让函数返回T *
  • @MarkRansom,我想在派生类之一中返回 My_struct*

标签: c++ templates polymorphism crtp


【解决方案1】:

兄弟!尝试切换到 C++14 并使用以下 sn-p 作为提示:

template <typename Derived>
struct base
{
 template <typename T>
 auto f(T x)
 {
  return static_cast<Derived&>(*this).f_impl(x);
 }

 auto g()
 {
  return static_cast<Derived&>(*this).g_impl();
 }
};

struct derived : base<derived>
{
 bool f_impl(int x)
 {
  return true;
 }

 double g_impl()
 {
  return 4.2;
 }
};

此片段取自here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-03
    • 2018-01-07
    • 2016-02-12
    • 1970-01-01
    • 2020-03-08
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多