Lambda中与任何类型匹配的伪参数
Dummy arguments in lambdas that will match any type?
假设我有这样的东西:
struct Foo {};
struct Bar {};
struct Baz {};
// ...
void RegisterListener1(std::function<void(Foo)>);
void RegisterListener2(std::function<void(Bar)>);
void RegisterListener3(std::function<void(Baz)>);
其中Foo
、Bar
和Baz
之间没有关系。
现在,假设我想给每个Register函数传递一个相同的lambda,会忽略其参数。我能在lambda的参数列表中放些什么吗?意思是"匹配这里的任何东西;我无论如何都要把它扔掉"?
auto listener = []( /* what? */ ) { throw UnsupportedOperationException(); };
RegisterListener1( listener );
RegisterListener2( listener );
RegisterListener3( listener );
我可以使用函数模板而不是lambda,并做如下操作:
template<typename T>
void listener(T)
{
throw UnsupportedOperationException();
}
// ...
RegisterListener1( listener<Foo> );
RegisterListener2( listener<Bar> );
RegisterListener3( listener<Baz> );
但这很乏味,尤其是如果三个Register函数的函子参数本身是模板化的,因此没有简单的方法写出"内部"参数类型。在打字的过程中,我想到了另一个想法:
struct Anything
{
template<typename T> Anything(const T&) {}
};
// ...
auto listener = [](Anything) { throw UnsupportedOperationException(); };
RegisterListener1( listener );
RegisterListener2( listener );
RegisterListener3( listener );
事实上,我对此很满意,也许我不需要再问这个问题了,但还有更好的选择吗?
在C++14中,您可以[](auto&&){ throw UnsupportedOperationException(); }
。
在C++03中,您可以:
struct ignore_and_throw {
template<class T>
void operator()(T const&) const {
throw UnsupportedOperationException();
}
};
并作为听众传递ignore_and_throw()
。这个函数对象有一个template
operator()
,您不必为它指定参数,这样就省去了令人讨厌的类型名称retype。(ignore_and_throw
非常类似于C++14 lambda作为旁白产生的内容)。
您的Anything
可能应该被称为sink_and_ignore
或ignore_arg
,并且是可以接受的。
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型