gpt4 book ai didi

c++ - 在其他函数模板、参数中使用推导类型

转载 作者:太空宇宙 更新时间:2023-11-04 11:42:06 25 4
gpt4 key购买 nike

我有函数模板:

template<class Ty, 
typename std::enable_if< std::is_arithmetic<Ty>::value >::type* = nullptr >
inline void printBars(std::vector<Ty> const& y,
std::function<Ty(Ty)> const& alt);

我想知道是否有某种方法可以在第二个参数中使用从第一个函数参数推导出的类型,以便能够以这种方式使用此函数模板:

#include <cmath>
printBars(y, log10);

有吗?

最佳答案

任何计算机科学问题都可以通过另一个间接级别来解决。

在公共(public)函数中,只需让第二个参数为 U 类型,第二个模板参数,并将调用转发给真正的函数实现。

例如,如果您想区分数组和指针参数,这种方法也是必要的。


例子。

namespace detail{
template< class T >
void printBars( std::vector<T> const& y, std::function<T(T)> const& alt)
{
// whatever.
};
} // namespace detail

template<
class T, class U,
class enabled = std::enable_if< std::is_arithmetic<T>::value >::type >
void printBars( std::vector<T> const& y, U const& alt )
{
detail::printBars_impl<T>( y, alt );
};

免责声明:编译器未亲手编写代码,+ 刚下床(还没喝咖啡)。 ;-)


考虑一下,这里最好的办法可能是按照 Xeo 的建议去做,完全放弃 std::function,因为它似乎只是对调用者施加了不合理的约束;相反,只需检查参数是否支持您想要使用它的目的。

关于c++ - 在其他函数模板、参数中使用推导类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21005313/

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