`
ah_fu
  • 浏览: 223293 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

template学习:一个Functor的使用例子

阅读更多

#include 
<stdio.h>

// 模板,可以调用函数或者Functor
template <typename Functor>
void TestTemplate(Functor func)
...{
    func(
"TestTemplate");
}


// C函数风格
void TestFunction(const char* str)
...{
    printf(
"TestFunction:%s ", str);
}


// Functor风格
struct TestFunctor
...{
    
void operator()(const char* str)
    
...{
        printf(
"TestFunctor:%s ", str);
    }

    TestFunctor()
    
...{
        printf(
"TestFunctor() ");
    }

    
~TestFunctor()
    
...{
        printf(
"~TestFunctor() ");
    }

}
;

int main()
...{
    TestTemplate(TestFunction);  
//函数指针作为调用参数
    printf("========================================== ");
    TestTemplate( TestFunctor() );  
//Functor临时对象作为调用参数
    printf("========================================== ");
    TestFunctor obj;  
//生成一个Functor的实例
    TestTemplate<TestFunctor&>(obj);  //使用引用类型来调用,避免拷贝
    return 1;
}

 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics