c – 递归模板?
发布时间:2020-12-16 09:29:56 所属栏目:百科 来源:网络整理
导读:重新提问 我发现我原来的问题不够明确,而且回复者误解了我的问题.所以让我试着澄清一下: 假设我有两个类: struct C { void(*m_func)(C*); };struct D { std::functionvoid(D*) m_func; }; 现在我想制作两者的通用版本,所以我这样做: templatetypename Fun
重新提问
我发现我原来的问题不够明确,而且回复者误解了我的问题.所以让我试着澄清一下: 假设我有两个类: struct C { void(*m_func)(C*); }; struct D { std::function<void(D*)> m_func; }; 现在我想制作两者的通用版本,所以我这样做: template<typename Func> struct G { Func m_func; }; 但是现在我不知道如何实例化这个类: G<void(*)(G*)> c; //error G<std::function<void(G*)>> d; //error G<void(*)( G<void(*)(G<???>*)> *)> c; //??? G<std::function<void( G<std::function<void(G<???>*)>> *)>> d; //??? 原始问题: 嗨, 我有一个模板类,可以将函数指针或std :: function对象作为其参数.一切都很好,直到该函数在其签名中使用模板类的指针: #include <functional> template<typename Func> class C { public: C() {} Func m_func; }; void foo() { C<void(*)(C*)> c; C<std::function<int(C*)>> d; } 相关的编译器错误: error C2955: 'C' : use of class template requires template argument list error C3203: 'function' : unspecialized class template can't be used as a template argument for template parameter 'Func',expected a real type error C2955: 'std::tr1::function' : use of class template requires template argument list 它是如何解决这个问题的? 解决方法
您不能在自身外部命名递归模板,但可以在内部命名,因为参数列表在自引用中是可选的.
然后问题就是告诉模板如何将自己传递给“某事”. template< typename T > struct fptr_taking_type { // this template is essentially a function typedef void (*type)( T ); // from types to types,the result being }; // the typedef template< typename T > struct stdfn_taking_type { typedef function< void (*)( T ) > type; }; template< template< typename > class F > struct G { typename F< G * >::type m_func; // this declares the member variable }; ... G< fptr_taking_type > q; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |