我希望将模板方法中的一些代码移动到非模板方法中,以减小二进制文件的大小。
有一个名为'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;
}
我的猜测是这不可能完成,尽管我正在使用的 native 编译器没有通过错误。
然而,还有另一个现有代码,其中类似的概念工作得很好
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)
{
................
................
}
最佳答案
模板函数调用普通的非模板函数以执行不需要或不使用任何模板参数的大块代码是很常见的。这是避免模板生成的代码膨胀的常用技术。
在你的例子中,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>
是模板参数,这将使它成为一个普通函数,并且它当然可以从模板函数中调用,并具有匹配的参数。
模板函数可以做普通函数做的任何事情,包括调用其他函数或使用其他模板。要求与任何其他函数相同:匹配函数参数类型等...
关于c++ - 我可以使用模板参数作为非模板方法的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291748/