gpt4 book ai didi

c++ - 通过元编程选择函数

转载 作者:太空宇宙 更新时间:2023-11-03 10:44:14 26 4
gpt4 key购买 nike

假设以下两个功能可能由用户提供也可能不提供:

void foo(int) { std::cout << "foo int" << std::endl; }
void foo() { std::cout << "foo void" << std::endl; }

在我的实现中,如果用户定义了它,我想调用 foo(int),否则调用 foo()。这可以按如下方式完成:

template<class Int> auto call_foo(Int i) -> decltype(foo(i)) { return foo(i); }
template<class... Int> void call_foo(Int... i) { return foo(); }

但是,如果我们想做相反的事情,即更喜欢 foo() 而不是 foo(int),那么下面的幼稚尝试是行不通的。

template<class Int> auto call_foo(Int i) -> decltype(foo()) { return foo(); }
template<class... Int> void call_foo(Int... i) { return foo(i...); }

问题是 decltype(foo()) 不依赖于 Int,所以 foo() 可能不存在不会导致 SFINAE。

一个可能的解决方案是要求用户定义其中之一

void foo(int, void*) { std::cout << "foo int" << std::endl; }
void foo(void*) { std::cout << "foo void" << std::endl; }

像这样,我们总是有一个 foo 参数,我们可以在其上执行“模板与参数包”技巧。虽然这在技术上解决了问题,但它非常丑陋,因为它需要用户采用一个附加参数,其含义对他/她来说可能并不明显。那么有没有办法在额外参数的情况下实现同样的效果?

最佳答案

不需要 SFINAE。只需标准的重载解析就足够了。

void call_func(void (*f)(), int) { f(); } // #1

template<class = void>
void call_func(void (*f)(int), int x) { f(x); } // #2

call_func(foo, 1); // #1 is preferred if viable. All others being equal,
// non-templates are preferred over templates

关于c++ - 通过元编程选择函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26175171/

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