首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++11 bind有关问题

2014-01-12 
c++11 bind问题本帖最后由 jianpanlanyue 于 2014-01-07 14:19:08 编辑#include iostream#include func

c++11 bind问题
本帖最后由 jianpanlanyue 于 2014-01-07 14:19:08 编辑 #include "iostream"
#include <functional>
using namespace std;

template<typename _Callback = void(*)()>
void fun(char* param, _Callback _callback = NULL){
        cout<<param<<endl;
        if(_callback)                //如果提供了回调,则调用。  但是这个地方编译报错。
                _callback();
}

void test(const char* param){
        cout<<param<<endl;
}

int main(int argc, char* argv[]){
        fun("fun param",std::bind(test,"test param"));
        return 0;
}

请教下,判断是否提供了回调函数的这地方,该怎么写?
[解决办法]

#include "iostream"
#include <functional>

using namespace std;

//typedef void (*_Callback)(const char *);
template<typename _Callback = void (*)()>
void fun(char* param, _Callback _callback = NULL)
{
        cout<<param<<endl;

        if(std::is_bind_expression<decltype(_callback)>::value)     //如果提供了回调,则调用。  但是这个地方编译报错。
                _callback();
}

void test(const char* param)
{
        cout<< param <<endl;
}

int main(int argc, char *argv[])
{
        fun("fun param", std::bind(test,"test param"));
        return 0;
}


std::is_bind_expression<decltype(_callback)>::value
[解决办法]

#include <iostream>
#include <functional>
using namespace std;

//for callable object
template<typename _Callback>
void fun(char const* param, _Callback _callback){
cout << param << endl;
_callback();
}

//for function pointer
template<typename _Callback>
void fun(char const* param, _Callback* _callback){
cout << param << endl;
if (_callback)
_callback();
}
void test(const char* param){
cout << param << endl;
}

void helloworld(){
cout << "helloworld" << endl;
}

int main(int argc, char* argv[])
{
fun("hello world", helloworld);
fun("fun param", std::bind(test, "test param"));
return 0;
}

热点排行