简体   繁体   English

继承的模板类的构造函数

[英]constructor for inherited template class

In the following code, I want to keep inheritance class B : public A<F> , but want to pass globalFunction() only to A and accessed from B as A::f1() and A::fa(). 在下面的代码中,我想保留继承class B : public A<F> ,但只想将globalFunction()传递给A并从B作为A :: f1()和A :: fa()进行访问。 How can I do that? 我怎样才能做到这一点?

#include <iostream>

void globalFunction()
{ }

//passing function to class A from main()
template<typename F>
class A
{
public:
    F f1;
    A(F fun1) : f1(fun1) {}
    void fa() {  f1();  } ;
};


template<typename F>
class B : public A<F>
{
public:
    B (F fun2) : A<F>(fun2) {}
    void fb() ; 
};

template<typename F>
void B<F>::fb() { A<F>::f1(); }

int main()
{
    A obja(globalFunction);
    obja.fa();
    B objb(globalFunction);
    objb.fb();
}

Basically I want to avoid making B as B<F> . 基本上,我想避免将B设为B<F> Does inheriting A<F> to B makes B also a template B<F> ? A<F>继承到B会使B成为模板B<F> I am not using template argument F anywhere in B , it is just inherited from A and using from B as A<F>::f1() 我不在B任何地方使用模板参数F ,它只是从A继承而来A并且从B用作A<F>::f1()

User will pass function globalFunction to templated argument so, class B : public A<decltype(globalFunction)> cannot be used. 用户会将函数globalFunction传递给模板化参数,因此, class B : public A<decltype(globalFunction)>不能使用class B : public A<decltype(globalFunction)>

If you know that your functor type is always going to be a function of a certain signature, you can get rid of templates altogether: 如果您知道函子类型将始终是某个签名的函数,则可以完全摆脱模板:

void globalFunction()
{ }

//passing function to class A from main()

class A
{
public:
    using fptr_t = void (*)();
    fptr_t f1;
    A(fptr_t fun1) : f1(fun1) {}
    void fa() {  f1();  } ;
};


class B : public A
{
public:
    B (fptr_t fun2) : A(fun2) {}
    void fb() ; 
};

void B::fb() { A::f1(); }

int main()
{
    A obja(globalFunction);
    obja.fa();
    B objb(globalFunction);
    objb.fb();
}

That is slightly detrimental to performance, since you would not be able to inline calls to your function pointers, but it does get rid of a template as requested. 这将对性能造成少许损害,因为您将无法内联调用函数指针,但确实会按要求删除模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM