在其他函数模板中使用推导类型,参数

Using deduced types in other function templates, argument

本文关键字:类型 参数 其他 函数模板      更新时间:2023-10-16

我有函数模板:

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);

有吗?

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

在公共函数中,只需让第二个参数的类型为 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 );
};

免责声明:代码没有被compilar的手碰过,+刚上床(还没有咖啡)。


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