【发布时间】:2012-11-19 15:05:02
【问题描述】:
我已经定义了名为CallBackAtInit 的类模板,其唯一目的是在其初始化时调用一个函数(构造函数)。该函数在模板参数中指定。问题是模板不接受std::function 作为参数;但他们接受函数指针。为什么?
这是我的代码:
#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;
}
【问题讨论】:
-
你能发布你的编译错误吗?
-
@Jean-Marie 不走寻常路。 main.cpp:4:115:错误:'struct std::function
' 不是模板常量参数的有效类型 -
我认为您应该更新您的问题标题和/或正文,以明确您指的是 non-type 参数。 std::function 是一个有效的模板参数,即
<typename std::function<()>>,它只是作为非类型参数无效
标签: c++ templates c++11 function-pointers std-function