c++ - C++中没有参数可变参数模板函数

标签 c++ function variadic-templates

template <bool ...T> 
int some_function()
{
  // this is the function with return type int
  // I am not sure how to get the values into the function
}

// this is how I want to call the function
int temp = some_function<1,0,0,0>();

对函数声明有什么建议吗?

最佳答案

对于您的用例,您可以使用递归来完成您想要的事情。为此,您需要两个重载。一个只有一个 bool(boolean) 参数,另一个带有两个 bool(boolean) 参数加上可变参数部分。这样您就可以在遍历参数包的过程中分别访问每个值。在这种情况下,

// quick and dirty pow fucntion.  There are better ones out there like https://stackoverflow.com/a/101613/4342498
template <typename T, typename U>
auto pow(T base, U exp)
{
    T ret = 1;
    for (int i = 0; i < exp; ++i)
        ret *= base;
    return ret;
}

template <bool Last>
int some_function()
{
    return Last;
}

template <bool First, bool Second, bool... Rest> 
int some_function()
{
    return First * pow(2, sizeof...(Rest) + 1) + some_function<Second, Rest...>();
}

int main()
{
    std::cout << some_function<1,0,0,0>();
}

哪个输出:
8

关于c++ - C++中没有参数可变参数模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60711154/

相关文章:

python - 如何在 Python 中让函数在 5 秒后返回?

c++ - 如何更改 MSVC++ 的 std::tuple 支持的模板参数的数量?

c++ - 将包装器对象用作具有可变模板和引用参数的 RValue

c++ - 从默认参数推导参数包

c++ - MySQL select for update,多线程超时

c++ - 提高通过 ctypes 将数据从 Python 传递到 C(++) 的速度

c++ - 在模板中使用 'export' 关键字时解决此错误?

r - 嵌套函数环境选择

C++ 应用程序 : How to properly delete/release an allocated object?

javascript - 循环函数返回未定义