gpt4 book ai didi

C++ 模板 : call whichever function matches between 2 choices

转载 作者:太空狗 更新时间:2023-10-29 20:55:21 25 4
gpt4 key购买 nike

如何使用C++模板调用匹配的函数?例如,如果我有函数 a 和 b:

void a_impl(string, int){}
void b_impl(int, string){}

template<typename X, typename Y>
void a(X x, Y y){
a_impl(x, y);
}

template<typename X, typename Y>
void b(X x, Y y){
b_impl(x, y);
}

template<typename X, typename Y>
void a_or_b(X x, Y y);

我如何实现 a_or_b 使其在匹配时调用 a(x, y),否则调用 b(x, y)?


我想要做的是一个可以处理这些情况的 for_each 函数:

vector<pair<string, int>> v1 = {{"one", 1}, {"two", 2}};

for_each(v1, [](string x, int y){
cout << x << " " << y << endl;
});

vector<int> v2 = {1, 2, 3};

for_each(v2, [](int x){
cout << x << endl;
});

到目前为止,我已经独立地为元组和单个变量工作,但我希望自动选择适当的版本。到目前为止,这是我的实现; unpack 是来自此页面的apply_from_tuple http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html .

template<typename Range, typename Func>
void for_each_unpack(Range && range, Func && func){
for (auto && element : range){
using Element = decltype(element);
unpack(std::forward<Func>(func), std::forward<Element>(element));
}
}

template<typename Range, typename Func>
void for_each_nounpack(Range && range, Func && func){
for (auto && element : range){
using Element = decltype(element);
std::forward<Func>(func)(std::forward<Element>(element));
}
}

编辑:多亏了@jotik,它才开始工作。我把代码放在github上https://github.com/csiz/for_each .

最佳答案

使用 decltype 的尾随返回类型和 SFINAE :

#include <iostream>
#include <string>
#include <utility>


void a(std::string, int) { std::cout << "a" << std::endl; }
void b(int, std::string) { std::cout << "b" << std::endl; }

template <typename ... Args>
auto a_or_b(Args && ... args)
-> decltype(a(std::forward<Args>(args)...))
{ return a(std::forward<Args>(args)...); }

template <typename ... Args>
auto a_or_b(Args && ... args)
-> decltype(b(std::forward<Args>(args)...))
{ return b(std::forward<Args>(args)...); }

int main() {
std::string s;
int i;
a_or_b(s, i); // calls a
a_or_b(i, s); // calls b
}

我在上面的例子中使用了完美转发,因为它避免了每个参数的拷贝,但是具有显式类型的不太通用的朴素解决方案也有效:

template <typename X, typename Y>
auto a_or_b(X x, Y y) -> decltype(a(x, y))
{ return a(x, y); }

template <typename X, typename Y>
auto a_or_b(X x, Y y) -> decltype(b(x, y))
{ return b(x, y); }

SFINAE 在这种情况下的工作方式如下。请注意,a_or_b 有 2 个模板定义。 .当你写一个函数调用给 a_or_b编译器试图找出哪个 a_or_b你本来想打电话的由于 SFINAE,它忽略任何模板 a_or_b它无法推断出其类型。例如。电话 a_or_b(s, i); (尾随)返回类型 decltype(b(std::forward<Args>(args)...))第二个a_or_b定义不起作用,因此第二个 a_or_b编译器不考虑定义。

在这种情况下,返回类型必须是尾随返回类型,因为它取决于函数参数。例如,以下不会编译:

template <typename ... Args>
decltype(b(std::forward<Args>(args)...)) a_or_b(Args && ... args)
{ return b(std::forward<Args>(args)...); }

关于C++ 模板 : call whichever function matches between 2 choices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35959463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com