根据可调用者的签名自动选择一元或二进制std :: transform函数重载

问题描述 投票:2回答:1

[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
}

[在此,我定义了两个lambda运算-一个一元和一个二进制(UnaryOpBinaryOp)–从GenericTransformer()传递到main()

GenericTransformer()内,我可以使用什么编译时魔术来基于std::transform()参数的函数签名自动选择两次operation调用中的哪一个?

注意:这是出于示例目的的简化情况。我不希望不必将GenericTransformer()拆分为两个单独的函数(一元函数和二进制函数),因为那样会导致此处没有显示的许多代码重复。坚持DRY理念!

c++ lambda dry template-meta-programming compile-time
1个回答
0
投票

使用C ++ 17,您可以将if constexprstd::is_invocable混合:

std::is_invocable
© www.soinside.com 2019 - 2024. All rights reserved.