C++ 在其他函数模板中使用推断类型,参数
我有一个函数模板:C++ 在其他函数模板中使用推断类型,参数,c++,function,templates,C++,Function,Templates,我有一个函数模板: 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); temp
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);
template::type*=nullptr>
内嵌空心打印条(标准::矢量常量和y,
std::函数const和alt);
我想知道是否有某种方法可以在第二个参数中使用从第一个函数参数推导出的类型,以便能够以这种方式使用此函数模板:
#include <cmath>
printBars(y, log10);
#包括
打印条(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 );
};
名称空间详细信息{
模板
无效打印栏(标准::向量常量和y,标准::函数常量和alt)
{
//不管怎样。
};
}//名称空间详细信息
模板<
T类,U类,
class enabled=std::enable_如果::type>
无效打印栏(标准::矢量常量和y、U常量和alt)
{
详图:打印条(y、alt);
};
免责声明:编译器的手并没有碰过代码,+刚刚起床(还并没有咖啡)。;-)
仔细想想,这里最好的方法可能是按照Xeo的建议去做,完全不用
std::function
,因为它似乎只是对调用者施加了一个不合理的约束;相反,只需检查参数是否支持您想要使用它的目的。您可以将第二个参数设置为“不可导出的上下文”,例如在标识类型trait中包装Ty
。我建议不要在签名中使用std::function
,但这可能是滥用。拿。。。F级。。。对于alt…
和可能的constraint/static assert onCallable
@Xeo,我尝试使用这样的标识类型特征:模板结构类型\u help{typedef T type;};模板::type*=nullptr>inline void打印条(std::vector const&y,std::function const&alt)代码>但这并没有奏效:(我不理解你的建议。你是在建议用alt成员函数创建一个模板类F吗?检查Alf的答案,他详细阐述了我在其中的意思。关于“身份”trait,我搞错了。-整个参数类型需要包装。谢谢你的回答!我希望能够使用任何类型的可调用实体,如lambda、常规函数、函数对象。我如何检查?