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

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

Those are the binary version of the actual decimal number. I want to reconstruct the decimal number with those binaries.

虽然您可以更高效地执行此操作,但 std::bitset 提供了一个非常简单的解决方案 (live example):

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.
}

对于你的用例,你可以使用递归来做你想做的事。为此,您需要两个重载。一个只有一个 bool 参数,另一个有两个 bool 参数加上可变参数部分。这使您可以在递归参数包时单独访问每个值。在这种情况下,它看起来像

// quick and dirty pow fucntion.  There are better ones out there like 
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

Those are the binary version of the actual decimal number. I want to reconstruct the decimal number with those binaries. I assume that I can do it when I get those binary numbers somehow!

如果你能用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;
 }