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

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

本文关键字:函数 lambda 调用 参数 对象 默认      更新时间:2023-10-16

我想要一个方法,该方法以默认值为参数的函数对象,用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)这是编译器不支持的功能吗?

您的测试显示情况确实如此。它是一个标准特性,因此不支持它意味着编译器不符合标准。

2)两者之间有什么区别吗?

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