Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 2在没有任何循环、递归或库函数的情况下提升到幂n_C++_Templates - Fatal编程技术网

C++ 2在没有任何循环、递归或库函数的情况下提升到幂n

C++ 2在没有任何循环、递归或库函数的情况下提升到幂n,c++,templates,C++,Templates,下面的程序在不使用任何循环、运行时递归或库函数[pow]的情况下计算2的幂n。 它使用模板元编程技术 #include <iostream> using namespace std; template<int n> struct funStruct { enum { val = 2*funStruct<n-1>::val }; }; template<> struct funStruct<0> { enum { va

下面的程序在不使用任何循环、运行时递归或库函数[pow]的情况下计算2的幂n。
它使用模板元编程技术

#include <iostream>
using namespace std;

template<int n> struct funStruct
{
    enum { val = 2*funStruct<n-1>::val };
};

template<> struct funStruct<0>
{
    enum { val = 1 };
};

int main()
{
    cout << funStruct<8>::val << endl;
    return 0;
}
#包括
使用名称空间std;
模板结构funStruct
{
枚举{val=2*funStruct::val};
};
模板结构funStruct
{
枚举{val=1};
};
int main()
{

cout这是一种显而易见的解决方案:

unsigned int power_of_two(unsigned int power) {
    return (1 << power);
}
unsigned整数幂(unsigned整数幂){

return(1正如@tdammes指出的,显而易见的解决方案只是一种非迭代的非递归方法:

constexpr int pow2( unsigned pwr ) {
   return 1 << per;
}
这与元编程技巧基本上是相同的编译时递归,更简洁易读。当然,使用
constepr
需要C++11,因此如果没有,您可以始终使用原始元编程技巧或@tdammers方法:

template <unsigned int N>
struct pow2 {
   static const unsigned int value = 1 << N;
};
模板
结构pow2{

static const unsigned int value=1这怎么不使用递归呢?它发生在编译时-但这很明显,因为参数是作为模板参数传递的,所以计算也发生在编译时。这个特定元编程示例的要点是2^n是(递归)计算的在编译时,而不是运行时。在第一个代码示例中,per=>pwr存在键入错误。
template <unsigned int N>
struct pow2 {
   static const unsigned int value = 1 << N;
};