Tag: crtp

为什么自动返回types扣除没有完全定义的types工作?

考虑以下: template<typename Der> struct Base { // NOTE: if I replace the decltype(…) below with auto, code compiles decltype(&Der::operator()) getCallOperator() const { return &Der::operator(); } }; struct Foo : Base<Foo> { double operator()(int, int) const { return 0.0; } }; int main() { Foo f; auto callOp = f.getCallOperator(); } 我想根据派生类中operator()签名在CRTP基类中创build一个返回types的成员函数。 然而decltype(&Der::operator())不能编译; Foo的operator()成员函数不可见。 我认为这是因为基类模板在Foo完全定义之前被实例化。 令人惊讶的是,如果我放置auto返回types它编译。 […]

“奇怪的循环模板模式”的实际应用

什么是“ 奇怪的循环模板模式 ”的一些实际用途? 通常显示的“ 计数class ”例子对我来说不是一个令人信服的例子。

无效的使用不完整的types

我想在我的项目中使用一个子类的typedef,我在下面的例子中隔离了我的问题。 有谁知道我要去哪里错了? template<typename Subclass> class A { public: //Why doesn't it like this? void action(typename Subclass::mytype var) { (static_cast<Subclass*>(this))->do_action(var); } }; class B : public A<B> { public: typedef int mytype; B() {} void do_action(mytype var) { // Do stuff } }; int main(int argc, char** argv) { B myInstance; return 0; } 这是我得到的输出: sean@SEAN-PC:~/Documents/LucadeStudios/experiments$ […]

CRTP来避免dynamic多态性

如何在C ++中使用CRTP来避免虚拟成员函数的开销?

C ++静态多态(CRTP)并使用派生类的typedef

我阅读了维基百科有关在C ++中使用静态(读:编译时)多态性的好奇的循环模板模式的文章 。 我想概括它,以便我可以根据派生types更改函数的返回types。 (这看起来应该是可能的,因为基types从模板参数中知道派生types)。 不幸的是,下面的代码不会使用MSVC 2010进行编译(我现在还没有轻松访问gcc,所以我还没有尝试过)。 任何人知道为什么 template <typename derived_t> class base { public: typedef typename derived_t::value_type value_type; value_type foo() { return static_cast<derived_t*>(this)->foo(); } }; template <typename T> class derived : public base<derived<T> > { public: typedef T value_type; value_type foo() { return T(); //return some T object (assumes T is default constructable) } […]

奇怪的循环模板模式(CRTP)是什么?

没有提到一本书,任何人都可以提供一个很好的解释CRTP的代码示例?