给定一个基类,它包含公共静态方法,该方法具有所有派生类的通用逻辑(例如创建它们)。子类模板的参数化类型被传递给基类模板(以及子类的类型,以便在基类的静态方法中访问其自定义静态方法)。这些类型的组合是typedefed新的“类型”(这是在基类中完成的,以避免重复某些代码)。然后,他们在派生类的公共部分中重新定义(类似)。我会将这些类型定义用于包含帮助程序的类中,如下所示:
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
template< class DERIVED >
class HELPERS;
template< class V, class DERIVED >
struct BASE
{
typedef typename V::value_type F;
static
F some_common_operation()
{
return helpers.approximate_x(DERIVED::value()); // some common logic (HELPERS::approximate_x() here) depending on the value of DERIVED::value()
}
static
DERIVED create_biased(F const & x)
{
return DERIVED(F(0.5) * (x + some_common_operation()));
}
protected :
BASE(F const & x_)
: x(x_)
{ ; }
F x;
private :
static
HELPERS< DERIVED > const helpers;
};
template< class V, class DERIVED >
HELPERS< DERIVED > const BASE< V, DERIVED >::helpers;
template< class V >
class DERIVED
: public BASE< V, DERIVED< V > >
{
typedef BASE< V, DERIVED< V > > B;
friend B;
public :
typedef typename B::F F;
DERIVED(F const & x_)
: B(x_)
{ ; }
F shape(F const & y) const
{
return y * x;
}
private :
static constexpr
F value()
{
return F(2.0L); // custom data
}
using B::x;
};
// template< class > class DERIVED1;...
template< class D >
struct HELPERS // set of helpers, that operates on classes derived from BASE
{
typedef typename D::F F; // error: no type named <F> in <class DERIVED<std::vector<double> >>
F approximate_x(F const & x) const
{
using std::sqrt;
return sqrt(x);
}
};
int main()
{
DERIVED< std::vector< double > > d(2.0L);
return EXIT_SUCCESS;
}
我正在尝试在helpers类中获取定义,但是我收到错误( g ++ -std = gnu ++ 11 a.cpp )。
a.cpp: In instantiation of «struct HELPERS<DERIVED<std::vector<double> > >»:
a.cpp:44:26: required from «struct BASE<std::vector<double>, DERIVED<std::vector<double> > >»
a.cpp:47:7: required from «class DERIVED<std::vector<double> >»
a.cpp:97:39: required from here
a.cpp:85:27: error: no type named «F» in «class DERIVED<std::vector<double> >»
有什么问题? Typedef及其所有“祖先”都可以在类链中访问(放在公共部分中)。
答案 0 :(得分:1)
这是一个鸡蛋问题。
这种情况正在发生,因为在您定义BASE
时,DERIVED
尚未完全定义(因为编译器需要首先解析基类)。因此,您无法访问DERIVED
中HELPER
的任何typedef。为了确保您可以检查以下内容不起作用:
template< class V, class DERIVED >
struct BASE
{
typedef typename V::value_type F;
typedef typename DERIVED::F G; // <-- error here
...
}
您可以尝试将HELPER
移至DERIVED
,或使用V
作为HELPER
的参数。