3

If I try to call a member function of a member of the base class from a template class on the other end of the inheritance hierarchy,

class memberobj {public: void bar(){}};

class basis {public: memberobj foo;};

template<class Base, class Derived>
class crtp : public Base { /* ... */ };

template<class Option>
class choice : crtp< basis, choice<Option> > {
  using basis::foo;
 public:
  void test () {foo.bar();}
};

class someoption {};

int main() {
  choice<someoption> baz;
  baz.test();
  return 0;
}

I get this error message:

g++-4.6 -o bin/crtptest crtptest.cpp
crtptest.cpp: In member function ‘void choice<Option>::test()’:
crtptest.cpp:12:21: error: ‘class basis’ has no member named ‘bar’
make: *** [bin/crtptest] Error 1

though bar is obviously a member of a member of basis, not of basis itself.
This does not happen with non-template final classes (of which a number are already in use, all deriving through the crtp intermediate class; so I wouldn't want to change anything about that), nor with a template class that directly derives from basis.

What's wrong here?

4

1 回答 1

3

你做错了方式:

 using basis::foo; //wrong way

是什么basis?它不是choice. 你应该这样做:

typedef crtp< basis, choice<Option> > base;
using base::basis::foo;

因为crtp< basis, choice<Option> >是类的基choice类,并通过它的基类foo成为成员。所以有细微的差别。choice

现在它可以工作了:http: //ideone.com/RPnyZ

于 2012-01-23T20:15:40.223 回答