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>();
对函数声明有任何建议吗?
这些是实际十进制数字的二进制版本。我想使用这些二进制文件来重建十进制数。
虽然您可以更高效地执行此操作,但是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.
std::string 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.
}
对于您的用例,您可以使用递归来完成您想要的事情。为此,您需要两个重载。一个只有一个布尔参数,另一个带有两个布尔参数加上可变参数部分。这样您就可以在遍历参数包的过程中分别访问每个值。在这种情况下,看起来像
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 First>
int some_function()
{
return First;
}
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