例如说我有两个简单的功能:
void a(int x)
{
//do something with x
}
void b(int x, float y)
{
// do something with x and y
}
我希望有一个带有可变数量args的单个函数,可以基于一个标志调用上述两个函数:
template<typename... Args>
void varArgs(bool a_or_b, Args... args)
{
if (a_or_b)
a(args...);
else
b(args...);
}
该标志将告诉我们我们要使用第一个功能还是第二个功能,但是由于模板是在编译时实例化的,因此将无法使用。我已经读过,constexpr if
但是我只能使用c ++ 14,所以我想知道是否还有其他选择?
编辑:布尔可以是一个编译时间常数,而不是运行时参数。
您可以做的任何事情constexpr if
,都可以使用标签分发。看起来像这样:
void a(int x)
{
//do something with x
}
void b(int x, float y)
{
// do something with x and y
}
template <typename ... Args>
void callImpl(std::true_type, Args && ... args) {
a(std::forward<Args>(args)...);
};
template <typename ... Args>
void callImpl(std::false_type, Args && ... args) {
b(std::forward<Args>(args)...);
};
template<bool callA, typename... Args>
void varArgs(Args&&... args)
{
callImpl(std::integral_constant<bool, callA>{}, std::forward<Args>(args)...);
}
int main() {
varArgs<true>(0);
varArgs<false>(0, 0.0);
}
这里的想法是,从varArgs
到的调用callImpl
将根据布尔值的不同而分派。为此,我们需要将布尔值提升为其他类型,这就是为什么我说布尔值必须是模板参数而不是值。实时示例:http://coliru.stacked-crooked.com/a/6c53bf7af87cdacc
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句