我想将任何类型的可调用对象(例如 lambda)透明地包装在另一个可调用对象中以注入附加功能。包装器的类型应与原始可调用对象具有相同的特征:
- 相同的参数类型
- 相同的返回类型
- 完美转发传递的参数
- 在 SFINAE 构造中使用时具有相同的行为
我尝试使用通用可变参数 lambda 作为包装器:
#include <iostream>
#include <type_traits>
template<class TCallable>
auto wrap(TCallable&& callable) {
return [callable = std::forward<TCallable>(callable)](auto&&... args) -> std::invoke_result_t<TCallable,decltype(args)...> {
std::cout << "This is some additional functionality" << std::endl;
return callable(std::forward<decltype(args)>(args)...);
};
}
int main(int argc, char *argv[])
{
auto callable1 = []() {
std::cout << "test1" << std::endl;
};
auto callable2 = [](int arg) {
std::cout << "test2: " << arg << std::endl;
};
auto wrapped1 = wrap(callable1);
auto wrapped2 = wrap(callable2);
static_assert(std::is_invocable_v<decltype(callable1)>); // OK
static_assert(std::is_invocable_v<decltype(wrapped1)>); // fails
static_assert(std::is_invocable_v<decltype(callable2), int>); // OK
static_assert(std::is_invocable_v<decltype(wrapped2), int>); // fails
}
正如评论中的static_assert
s 表明,包装器可调用对象的调用方式与原始可调用对象不同。为了实现所需的功能需要改变什么?
给定的示例是使用 Visual Studio 2017 (msvc 15.9.0) 编译的。
这可能是 MSVC 实现中的一个错误std::invoke_result
or std::is_invocable
(即使使用 Visual Studio 15.9.2,我也可以在此处重现该问题)。你的代码与 clang (libc++) 和 gcc 配合良好 https://godbolt.org/z/-rWdOy我看不出有什么理由不应该这样做。然而,你并不真正需要std::invoke_result
无论如何,你可以让你的 lambda 推断出返回类型:
template<class TCallable>
auto wrap(TCallable&& callable) {
return [callable = std::forward<TCallable>(callable)](auto&&... args) -> decltype(auto) {
std::cout << "This is some additional functionality" << std::endl;
return callable(std::forward<decltype(args)>(args)...);
};
}
那么似乎也可以与 MSVC 配合使用 https://godbolt.org/z/ounjrj…
编辑:正如 Piotr Skotnicki 在下面的评论中指出的那样,decltype(auto)将禁止SFINAE https://stackoverflow.com/questions/17608637/sfinae-and-decltypeauto。要解决此问题,您可以使用尾随返回类型:
template<class TCallable>
auto wrap(TCallable&& callable) {
return [callable = std::forward<TCallable>(callable)](auto&&... args) -> decltype(callable(std::forward<decltype(args)>(args)...)) {
std::cout << "This is some additional functionality" << std::endl;
return callable(std::forward<decltype(args)>(args)...);
};
}
这会需要更多的打字,但应该可以与 SFINAE 配合使用似乎也可以与 MSVC 配合使用 https://godbolt.org/z/e92TkX…
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)