例如假设我有两个简单的函数:
void a(int x)
{
//do something with x
}
void b(int x, float y)
{
// do something with x and y
}
我希望有一个带有可变数量参数的函数,它可以根据标志调用上述两个函数:
template<typename... Args>
void varArgs(bool a_or_b, Args... args)
{
if (a_or_b)
a(args...);
else
b(args...);
}
该标志会告诉我们是要使用第一个函数还是第二个函数,但是由于模板是在编译时实例化的,所以这是行不通的。我读过有关 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);
}
这里的想法是,从 varArgs
到 callImpl
的调用将根据 bool 值进行不同的调度。为此,我们需要将 bool 值提升为不同的类型,这就是为什么我说 bool 值需要是模板参数而不是值。现场示例:http://coliru.stacked-crooked.com/a/6c53bf7af87cdacc
关于c++ - 是否可以调用具有不同数量参数的函数,传递相同的参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252343/