nit*_*oid 1 c++ templates parameter-passing variadic-templates c++14
比如说我有两个简单的功能:
void a(int x)
{
//do something with x
}
void b(int x, float y)
{
// do something with x and y
}
Run Code Online (Sandbox Code Playgroud)
我希望有一个具有可变数量的args的单个函数,它可以根据标志调用上述两个:
template<typename... Args>
void varArgs(bool a_or_b, Args... args)
{
if (a_or_b)
a(args...);
else
b(args...);
}
Run Code Online (Sandbox Code Playgroud)
该标志将告诉我们是否要使用第一个或第二个函数,但是因为模板在编译时被实例化,所以这将不起作用.我读过constexpr if但是我只能使用c ++ 14所以我想知道是否有其他选择?
编辑:bool可以是编译时常量,而不是运行时参数.
你可以做任何事情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);
}
Run Code Online (Sandbox Code Playgroud)
这里的想法是,来自varArgsto 的调用callImpl将根据布尔值的不同而被调度.为此,我们需要将布尔值提升为不同的类型,这就是为什么我说布尔值需要是模板参数而不是值.实例:http://coliru.stacked-crooked.com/a/6c53bf7af87cdacc