if语句中的函数名以奇怪的方式转换

时间:2016-01-25 22:30:46

标签: c++ function types casting

使用此代码(有效的C ++ 11):

import UIKit
import Photos

class ViewController: UIViewController {

    var images:[UIImage] = [] // <-- Array to hold the fetched images

    override func viewDidLoad() {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM-dd-yyyy"
        fetchPhotosInRange(startDate: formatter.date(from: "04-06-2015")! as NSDate, endDate: formatter.date(from: "04-16-2015")! as NSDate)
    }

    func fetchPhotosInRange(startDate:NSDate, endDate:NSDate) {

        let imgManager = PHImageManager.default()

        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = true
        requestOptions.isNetworkAccessAllowed = true

        // Fetch the images between the start and end date
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "creationDate > %@ AND creationDate < %@", startDate, endDate)

        images = []

        let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
        // If the fetch result isn't empty,
        // proceed with the image request
        if fetchResult.count > 0 {
            // Perform the image request
            for index in 0  ..< fetchResult.count  {
                let asset = fetchResult.object(at: index)
                imgManager.requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData: Data?, dataUTI: String?, orientation: UIImageOrientation, info: [AnyHashable : Any]?) -> Void in
                    if let imageData = imageData {
                        if let image = UIImage(data: imageData) {
                            // Add the returned image to your array
                            self.images += [image]
                        }
                    }
                    if self.images.count == fetchResult.count {
                        // Do something once all the images
                        // have been fetched. (This if statement
                        // executes as long as all the images
                        // are found; but you should also handle
                        // the case where they're not all found.)
                        print(self.images)
                    }
                })
            }
        }
    }
}

问题出在#include <stdio.h> #include <typeinfo> bool my_awesome_func(int param) { return (param > 1); } int main(int argc, char const *argv[]) { fprintf(stderr, "type of my_awesome_func: %s\n", typeid(my_awesome_func).name()); if (my_awesome_func) { fprintf(stderr, "WHAT???\n"); } return 0; } 声明中。虽然if返回的内容看起来像typeid(我认为它是函数类型的gcc语言)但我不明白为什么这种类型被隐式转换为FbiE(仅举个例子,也适用于bool)。

为什么int语句编译并评估为真?

1 个答案:

答案 0 :(得分:9)

您的代码中没有强制转换。演员表是一种明确的转换。我假设你在问:函数隐式转换为bool会做什么?

答案是:函数转换为函数指针。然后通过隐式转换将函数指针转换为bool。该转换定义为屈服:

  • false表示空函数指针
  • true用于任何其他函数指针

因此,在您的代码中,始终输入if (my_awesome_func)的正文。 (将实际函数转换为函数指针永远不会产生空指针)。