本文介绍了为什么函数指针不为std :: function有效模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了名为 CallBackAtInit 的类模板,该模板仅用于在初始化时调用一个函数(构造函数)。该功能在模板参数中指定。问题在于模板不接受 std :: function 作为参数。但是它们接受函数指针。为什么?

I have defined class template named CallBackAtInit which only purpose is to call a function at its initialization (constructor). The function is specified in template parameters. The problem is that templates does not accept std::function as parameters; but they accept function pointers. Why?

这是我的代码:

#include <iostream>
#include <functional>

/* Does not work:*/     template <typename return_type, typename arg_type, std::function<return_type(arg_type)> call_back>
/* Work fine: *///      template <typename return_type, typename arg_type, return_type(*call_back)(arg_type)>

class CallBackAtInit {
public:
    CallBackAtInit(arg_type arg)
    {
        call_back(arg);
    };
};

void printInt(int i);

class HoldInt : private CallBackAtInit<void, int, printInt> {
public:
    HoldInt(int integer)
    : CallBackAtInit(integer)
    {}
    // ...
};

int main(int argc, char** argv)
{
    HoldInt hi(10);
    return 0;
}

void printInt(int i)
{
    std::cout << i << std::endl;
}


推荐答案

参数用于模板定义可以有四种:

The parameter for a template definition can be of four kinds:


  • 仅接受 type 的参数(或 template 类型)。

  • 参数,该参数只能接受整数值

  • 参数,其中只能接受指针到成员的值

  • std :: nullptr_t (自C ++起) 11)

  • parameter which can accept only type (or template type).
  • parameter which can accept only integral value.
  • parameter which can accept only pointer-to-member value.
  • std::nullptr_t (since C++11)

当您在模板定义中提及 std :: function 时,那么它既不属于上述类别。模板不能接受 types ,也不能接受 integral value pointer-to-member value

When you mention std::function in a template definition, then it falls neither of the above categories. The template cannot accept types, nor can it accept integral value, or pointer-to-member value.

当参数为函数指针类型时,它可以接受函数指针(与该类型匹配的函数的地址),它只是一个整数值。请注意,地址始终是整数值。因此它属于第二类,这就是它起作用的原因。

When the parameter is function pointer type, then it can accept function-pointer (the address of a function matching the type) which is just an integral value. Note that address is always an integral value. So it falls into the second category, which is why it works.

这篇关于为什么函数指针不为std :: function有效模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 22:03