Apple LLVM3.1中的Blocks与GNU++11的兼容情况

测试结果非常可喜~

//
//  hello.mm
//  objCTest
//
//  Created by zenny_chen on 12-2-21.
//  Copyright (c) 2012年 GreenGames Studio. All rights reserved.
//

#import <Foundation/Foundation.h>

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

template <typename T>
void GeneralLambda4Type(T t)
{
    __block T var = T(100);
    
    // The type of the Block is: T(^)(T)
    auto a = ^(T i) {
        cout << "The value is: " << i << endl;
        var += i;
        return i + 1;
    };
    
    auto b = a(t);
    
    cout << "The returned value is: " << b << endl;
    
    cout << "The var is: " << var << endl;
}

template <typename T>
void GeneralLambda(void)
{
    T lam = ^(void){ };
    lam();
}

template <typename T>
void GeneralLambdaType(void (^lam)(T), const T &param)
{
    cout << "The parameter is: " << param << endl;
    
    // 函数对象也适用
    function<void(T)> func = lam;
    
    func(param);
}

// Block不能作为模板的非类型形参
//template <void (^LAMBDA)(int)>

extern "C" void HelloTest(void);

void HelloTest(void)
{
    GeneralLambda4Type(100);
    GeneralLambda<void(^)(void)>();
    GeneralLambdaType(^(int param){ cout << "The value is: " << param << endl; },
                      -100);
}

 

分析:为何Blocks不能作为模板的非类型形参?

由于Blocks的地址并不是在编译时即可确定的,而是在运行时确定。Blocks根据特定上下文也可能会被分配到特定的存储空间给特定的处理器核心执行,从而提升执行效率。因此Blocks与传统的函数指针以及函数引用不同,不能作为模板的非类型形参~

 

posted @ 2012-02-21 17:17  zenny_chen  Views(654)  Comments(0Edit  收藏  举报