C++ lambdas中匹配任何类型的伪参数?

C++ lambdas中匹配任何类型的伪参数?,c++,lambda,C++,Lambda,假设我有这样的东西: struct Foo {}; struct Bar {}; struct Baz {}; // ... void RegisterListener1(std::function<void(Foo)>); void RegisterListener2(std::function<void(Bar)>); void RegisterListener3(std::function<void(Baz)>); template<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)>);
template<typename T>
void listener(T)
{
   throw UnsupportedOperationException();
}

// ...

RegisterListener1( listener<Foo> );
RegisterListener2( listener<Bar> );
RegisterListener3( listener<Baz> );
我可以使用函数模板而不是lambda,并执行如下操作:

struct Foo {};
struct Bar {};
struct Baz {};

// ...

void RegisterListener1(std::function<void(Foo)>);
void RegisterListener2(std::function<void(Bar)>);
void RegisterListener3(std::function<void(Baz)>);
template<typename T>
void listener(T)
{
   throw UnsupportedOperationException();
}

// ...

RegisterListener1( listener<Foo> );
RegisterListener2( listener<Bar> );
RegisterListener3( listener<Baz> );
模板
空侦听器(T)
{
抛出UnsupportedOperationException();
}
// ...
寄存器Listener1(侦听器);
寄存器Listener2(侦听器);
寄存器Listener3(侦听器);
但是这很乏味,特别是如果三个寄存器函数的函子参数都是模板化的,因此没有简单的方法写出“内部”参数类型。这是我在打印过程中想到的另一个想法:

struct Anything
{
    template<typename T> Anything(const T&) {}
};

// ...

auto listener = [](Anything) { throw UnsupportedOperationException(); }; 
RegisterListener1( listener );
RegisterListener2( listener );
RegisterListener3( listener );
struct任何东西
{
模板任何内容(常量T&{}
};
// ...
自动侦听器=[](任何内容){抛出不支持的操作异常();};
寄存器Listener1(侦听器);
寄存器Listener2(侦听器);
寄存器Listener3(侦听器);
实际上我对此没意见,也许我不需要再问这个问题了,但是有更好的选择吗?

在C++14中,您可以
[](自动&){throw UnsupportedOperationException();}

在C++03中,您可以:

struct ignore_and_throw {
  template<class T>
  void operator()(T const&) const {
    throw UnsupportedOperationException();
  }
};
struct忽略和抛出{
模板
void运算符()(T常量和)常量{
抛出UnsupportedOperationException();
}
};
然后将
ignore\u和\u throw()
作为侦听器传递。此函数对象有一个
模板
操作符()
,您不必为其指定参数,从而为您节省了烦人的类型名称retype。(
ignore_and_throw
非常类似于C++14 lambda作为旁白生成的内容)


你的
任何东西
都应该被称为
sink\u和\u ignore
ignore\u arg
,这是可以接受的。

如果你正在创建一个结构,你最好放弃lambda,只使用一个函子。你说的是C++03,但可能是指C++11,因为你使用了右值引用。然而,对于被忽略的参数
const&
应该也能工作,并且在C++03中也能真正工作。@oberon是的,我只是在我现在不在乎的时候键入
T&
。)