Generic lambda argument for std::pair

拈花ヽ惹草 提交于 2019-12-03 06:51:00

You can constrain a lambda using enable_if:

auto confirmOperation = [](auto pr) ->
    std::enable_if_t<std::is_same<decltype(pr.second), bool>::value> {
  assert(pr.second);
};

Example.

You could define an implementation details template function:

template<typename T>
void lambda_impl(std::pair<T, bool> const &p) {
  assert(p.second);
}

and then call this in your lambda as:

auto f = [](auto p) { lambda_impl(p); };

The following scheme may be available in the future with the advent of Concepts-Lite. For the time being it works only on GCC:

auto f = [](std::pair<auto, auto> const &p) { assert(p.second); };

or even better:

auto f = [](std::pair<auto, bool> const &p) { assert(p.second); };

P.S Clang is correct not to compile this due to the fact that auto parameters are not part of C++14.

Seems like you could just use is_same and static_assert here:

[](auto pr){
    static_assert(is_same_v<decltype(pr.second), bool>);
    assert(pr.second);
};

Or if C++17 is not an option, a message to static_assert is required and you won't be able to use is_same_v:

[](auto pr){
    static_assert(is_same<decltype(pr.second), bool>::value, "ouch");
    assert(pr.second);
}

Live Example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!