CRTP和返回void的方法*

CRTP and method returning void *

本文关键字:方法 void 返回 CRTP      更新时间:2023-10-16

我使用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<My_struct>)必须提供get_data()实现
每个My_struct实例都包含来自设置文件某行的信息。

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

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

兄弟!尝试切换到C++14,并使用以下片段作为提示:
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;
}
};

这个碎片是从这里取下来的。