繁体   English   中英

C ++中的无参数可变参数模板函数

[英]No argument variadic template function in C++

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 参数,另一个有两个 bool 参数加上可变参数部分。 这使您可以在递归遍历参数包时单独访问每个值。 在这种情况下,看起来像

// 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

这些是实际十进制数的二进制版本。 我想用这些二进制文件重建十进制数。

虽然您可能可以更std::bitset执行此操作,但std::bitset提供了一个非常简单的解决方案(现场示例):

template <bool ...T> 
int some_function()
{
    static_assert(sizeof...(T) < sizeof(int) * CHAR_BIT); // We want this to fit in int with no negatives.

    char binary[]{(T + '0')...}; // Put corresponding '0's and '1's into a string.
    std::bitset<sizeof...(T)> bits(binary); // Use the string to make a bitset.
    return bits.to_ulong(); // Convert the bitset to a number.
}

这些是实际十进制数的二进制版本。 我想用这些二进制文件重建十进制数。 我假设当我以某种方式获得这些二进制数时我可以做到!

如果你可以使用C++17,那么也折叠,我想你可以写一些如下

template <bool ...T> 
int some_function ()
 {
   int ret{};

   return ((ret <<= 1, ret += T), ...);
 }

在 C++11 和 C++14 中不太优雅

template <bool ...T> 
int some_function ()
 {
   using unused = int[];

   int ret{};

   (void)unused { 0, (ret <<= 1, ret += T)... };

   return ret;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM