我希望将模板方法中的一些代码移到非模板方法中,以减少二进制文件大小。
有一个名为'Target'的模板类,如下所示
template<TargetType K, typename V = plat_target_handle_t>
class Target
{
.............
..............
};
TargetType是枚举数据类型。
template<>
template< TargetType T>
std::vector<Target<T> >
Target<TARGET_TYPE_X>::getChildren(const TargetState i_state) const
{
std::vector<Target<T> > l_children;
for ( int i=0; i < elements_in_some_list ; ++i)
{
/*If the current entry in some_list match my critera, add to the l_children */
}
}
TargetType是枚举数据类型,TARGET_TYPE_X是枚举值之一。
我想将所有逻辑移动到选择子项为全局方法,让我们说getChildrenHelper。
getChildrenHelper声明如下。
void getGhildrenHelper(const TargetType i_targetType,
const TargetState i_targetstate,
std::vector<Target<TARGET_TYPE_ALL>> & io_children);
然后getChildren方法最终看起来像
template<>
template< TargetType T>
std::vector<Target<T> >
Target<TARGET_TYPE_X>::getChildren(const TargetState i_state) const
{
std::vector<Target<T> > l_children;
childHelper(T,i_state,l_children);
return l_children;
}
我的猜测是无法做到这一点,尽管我正在使用的本机编译器没有出错。
然而,还有另一个现有的代码,其中类似的概念工作得很好
template< TargetType K >
inline ReturnCode putParam(const Target<K>& i_target,
const RingID i_ringID,
const RingMode i_ringMode)
{
ReturnCode l_rc = FAPI2_RC_SUCCESS;
// Find the string in the SEEPROM
l_rc = findInImageAndApply(i_target, i_ringID, i_ringMode);
return l_rc;
}
fapi2::ReturnCode findImageAndApply(
const fapi2::Target<fapi2::TARGET_TYPE_ALL>& i_target,
const RingID i_ringID,
const fapi2::RingMode i_ringMode)
{
................
................
}
答案 0 :(得分:1)
模板函数调用普通的非模板函数以执行不需要或使用任何模板参数的大块代码是很常见的。这是避免模板生成的代码膨胀的常用技术。
在您的情况下,TargetType
出现的是模板参数,并且没有此类。就这样:
void getGhildrenHelper(const TargetType i_targetType,
const TargetState i_targetstate,
std::vector<Target<TARGET_TYPE_ALL>> & io_children);
本身不应该编译,因为TargetType
似乎是模板参数,而不是类名,基于模板专业化中的代码。
但是,这里的代码可能不明确。在任何情况下,如果TargetType
和TargetState
以及Target<TARGET_TYPE_ALL>
都不是模板参数,这将使这成为一个普通的函数,并且它当然可以从模板函数调用,具有匹配的参数
模板函数可以执行普通函数所做的任何事情,包括调用其他函数或使用其他模板。要求与任何其他功能相同:匹配函数参数类型等...