NKa*_*tUT 7 c++ lambda dry compile-time template-meta-programming
std::transform提供采用一元(一个参数)或二元(两个参数)可调用操作(通常为 lambda)的重载。
我想将我想要的可调用对象作为参数传递给父函数,并使用编译时(例如模板元编程)方法std::transform根据传递的可调用对象是否具有带有一个的函数签名来自动选择使用哪个重载或两个论点。
这是用(尚未工作)代码表达的所需方法:
#include <algorithm>
auto UnaryOp = [](const auto& src) { return src; }; // simple copy
auto BinaryOp = [](const auto& src1, const auto& src2) {return src1 + src2; }; // accumulate
auto GenericTransformer = [](auto src, auto dst, auto operation) { // operation is unary OR binary
/* unrelated code */
// need to chose this one:
std::transform(src.begin(), src.end(), dst.begin(), operation);
// or this one:
std::transform(src.begin(), src.end(), dst.begin(), dst.begin(), operation);
// depending on whether unary or binary operation is passed in 'operation' argument
/* unrelated code */
};
int main() {
std::vector<int> source_vec(100);
std::vector<int> dest_vec(100);
GenericTransformer(source_vec, dest_vec, UnaryOp); // i.e. copy source to destination
GenericTransformer(source_vec, dest_vec, BinaryOp); // i.e. accumulate source into destination
}
Run Code Online (Sandbox Code Playgroud)
在这里,我定义了两个 lambda 操作——一个一元和一个二元(UnaryOp和BinaryOp)——它们被传递给GenericTransformer()from main()。
在 中GenericTransformer(),我可以使用什么编译时魔法来std::transform()根据operation参数的函数签名自动选择两个调用中的哪一个?
注意:这是出于示例目的的简化案例。我宁愿不必拆分GenericTransformer()为两个单独的函数(一元函数和二进制函数),因为这会导致此处未显示的大量代码重复。坚持 DRY 理念!
使用 C++17,您可以混合if constexpr和std::is_invocable:
if constexpr (std::is_invocable_v<
decltype(operation), decltype(*src.begin())>) {
std::transform(src.begin(), src.end(), dst.begin(), operation);
}
else {
std::transform(src.begin(), src.end(), dst.begin(), dst.begin(), operation);
}
Run Code Online (Sandbox Code Playgroud)
您还可以检查operation在第二种情况下是否有效,但这需要额外的else分支以避免在(两个分支都无效)时消除编译时错误,这将需要一些always_false恶作剧。