c++ - 是否可以调用具有不同数量参数的函数,传递相同的参数包

标签 c++ templates parameter-passing c++14 variadic-templates

例如假设我有两个简单的函数:

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);
}

这里的想法是,从 varArgscallImpl 的调用将根据 bool 值进行不同的调度。为此,我们需要将 bool 值提升为不同的类型,这就是为什么我说 bool 值需要是模板参数而不是值。现场示例:http://coliru.stacked-crooked.com/a/6c53bf7af87cdacc

关于c++ - 是否可以调用具有不同数量参数的函数,传递相同的参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252343/

相关文章:

c++ - Cmake import -lpthread 等

c++ - 分离轴定理 : Calculating the MTV for Polygon & Line Segment

c++ - Thread - 它是静态持续时间对象吗?

c++ - MacOS - 如何使用 C/C++ 获取具有 PID 的进程用户/所有者?

c++ - 模板函数中的参数推导失败

c++ - Lambda 表达式作为 C++14 中的类模板参数

c++ - 即使有包含保护,链接器也会提示多重定义

C# 可选参数/多个必需

java - 如果我从另一个类调用它,为什么我的 ArrayList 是空的?

javascript - 将参数传递给 JavaScript 文件