使用 lambda 调用的默认函数对象值作为函数参数

default function object value as function parameter to be called with a lambda

我想要一个带有默认值作为参数的函数对象的方法,用 lambda 函数调用,例如:

#include <iostream>
#include <functional>

void func(const std::function<void()>& f = {}){
  if(f) f();
  else std::cout << "or not" << std::endl;
}

int main() {
  func([](){ std::cout << "hello" << std::endl; });
  func();
}

但是在 Visual Studio 2012 上这不会编译(例如,它使用 Visual Studio 2015 或 g++ 编译),抱怨默认值 {}。将其更改为:

void func(const std::function<void()>& f = nullptr){

解决问题。 1)编译器不支持该功能吗? 2)两者有什么区别吗?

1) Is that a feature not supported by the compiler?

您的测试似乎表明是这种情况。是标准特性,不支持就是编译器不符合标准。

2) Is there any difference between both?

没有区别。默认构造函数和采用 nullptr_t 的构造函数的行为完全相同。