默认lambda作为函数的模板化参数 [英] Default lambda as templated parameter of a function

查看:156
本文介绍了默认lambda作为函数的模板化参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码

template<bool b, typename T> void foo(const T& t = []() {}) {
  // implementation here
}

void bar() {
  foo<true>([&](){ /* implementation here */ }); // this compiles
  foo<true>(); // this doesn't compile
}

如果没有编译,我出现以下错误:

In the case that doesn't compile I get the following errors:

error C2672: 'foo': no matching overloaded function found
error C2783: 'void foo(const T&)': could not deduce template argument for 'T'

我认为这很明显我要实现的目标:在有和没有客户端提供的lambda的情况下调用 foo 。编译器为MSVC ++ 2017版本15.4.4工具集v141。

I think it's clear what I want to achieve: let foo be called with and without a client-provided lambda. The compiler is MSVC++2017 version 15.4.4 toolset v141.

推荐答案

编译器使用参数 passed 推断模板类型。如果没有参数,那么编译器将如何推断模板类型?

The compiler uses the arguments passed to deduce the template type. If there's no arguments, then how would the compiler be able to deduce the template type?

您可以在此处使用 overloading 代替默认参数。

You can use overloading instead of default arguments here.

重载的非参数函数可以简单地使用默认参数调用该函数:

The overloaded non-argument function can simply call the function with the "default" argument:

template<bool b, typename T> void foo(const T& t) {
  // implementation here
}

template<bool b> void foo() {
  foo<b>([]() {});
}

这篇关于默认lambda作为函数的模板化参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆