函数/功能作为模板参数。它们可以存储吗? [英] Functions/functors as template parameters. Can they be stored?

查看:91
本文介绍了函数/功能作为模板参数。它们可以存储吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有以下自由函数和函子:

Imagine I have the following free function and functor:

void myFreeFunction(void)
{
    cout << "Executing free function" << endl;
}

struct MyFunctor
{
    void operator()(void)
    {
        cout << "Executing functor" << endl;
    }
};

这个答案,我可以将函数或函子作为模板参数传递给另一个函数:

As discribed by this answer, I can pass my function or functor as a template argument to another function:

template <typename F>
void doOperation(F f)
{
    f();
}

然后调用:

doOperation(myFreeFunction);
doOperation(MyFunctor());

到目前为止很好。但是,如果我想要以下内容,该怎么办:

So far so good. But what if I want something like the following:

template<typename Callback>
class MyClass
{
private:
    Callback mCallback;

public:
    MyClass(){}

    void execute()
    {
        mCallback();
    }
};

在这种情况下,我在声明类时指定函数/函数,但直到调用它后来。它适用于仿函数:

In this case I'm specifing the function/functor when I declare the class but not calling it until later. It works for functors:

MyClass<MyFunctor> myClass1;
myClass1.execute();

但不适用于功能:

MyClass<myFreeFunction> myClass2;
myClass2.execute();

编译器说:


错误C2923:'MyClass':'myFreeFunction'不是参数'Callback'的有效模板类型参数

error C2923: 'MyClass' : 'myFreeFunction' is not a valid template type argument for parameter 'Callback'

足够公平...但是您将如何构造它?

Which is fair enough... but how would you structure this?

注意:我知道std :: function并可能最终使用这个。不过,它的速度明显要慢一些,因此我正在研究所有选项。

Note: I'm aware of std::function and may end up using this. It's measurably slower though so I'm looking at all options.

谢谢

David

推荐答案

问题是,freefunction不是类型,而是of的元素(在这种情况下,是函数指针。

The problem is that freefunction is not a type but a element of a of (int this case a function pointer.

要解决此问题,您需要在构造函数中传递该函数,但是您仍然需要知道确切的类型。

to fix this problem you need to pass the function in, in construction, however you still need to know the exact type.

myclass<call_back_t> my_class(call_back);

编辑:在c中++ 11可以从 decltype(call_back)

In c++11 the type can be got from decltype(call_back)

获得类型,但是回叫会很麻烦创建生成器函数通常要容易得多

however getting the call back can be troublesome it is often a lot easier to create a generator function

//this should be in the namespace of the class or a static member of it
template<FuncType>
myclass<FuncType> make_class(FuncType func)
{
     return myclass<FuncType>(func);
}
//called like
myclass mc=make_class(&my_callback);

不要随意更改构造函数

template<typename CallBack>
myclass{
private:
   CallBack call_back;
public:
   myclass(CallBack call_back_)
   : call_back(call_back_)
   {}
};

或类似的东西

这篇关于函数/功能作为模板参数。它们可以存储吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆