现在的位置: 首页 > 综合 > 正文

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

2013年09月12日 ⁄ 综合 ⁄ 共 793字 ⁄ 字号 评论关闭

#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;
}

 

抱歉!评论已关闭.