相关疑难解决方法(0)

使用模板元编程计算阶乘

我不明白这段代码(来自维基百科)是如何工作的:

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
Run Code Online (Sandbox Code Playgroud)
  • 这个奇怪的模板是<int N>什么?
  • 这是第二个奇怪的模板是<>什么?
  • 有什么东西 enum
  • 使用此而不是正常的运行时因子计算有什么好处?
  • 你们多久使用一次这个?我一直在使用C++,但之前从未使用过.我错过了C++的一小部分?

谢谢!

c++ templates metaprogramming

22
推荐指数
2
解决办法
2万
查看次数

为什么C++中的void方法可以返回void值,但在其他语言中它不能?

该程序在C++中编译和运行,但不是Java和C#等多种语言.

#include <iostream>
using namespace std;

void foo2() {
  cout << "foo 2.\n";
}

void foo() {
    return foo2();
}

int main() {

    foo();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在Java中,这给出了编译器错误,如'Void方法无法返回值'.但由于被调用的方法本身就是一个void,因此它不返回值.我知道为了便于阅读,可能会禁止这样的结构.还有其他异议吗?

编辑:为了将来的参考,我在这里发现了一些类似的问题return-void-type-in​​-c-and-c 我个人认为这个问题还没有回答.回复'因为它在规范中这样说,继续'不会削减它,因为有人必须首先编写规范.也许我应该问'允许返回像C++这样的void类型有什么优缺点'?

c# c++ java void

14
推荐指数
1
解决办法
595
查看次数

templates <int T> C++

定义模板意味着什么template <int N>,我从书中的一个例子中读到这个:

typedef map<int, double> row;
template <int N> struct matrix;
{
   map <int, row> my_matrix;
}
Run Code Online (Sandbox Code Playgroud)

我经常看到模板,然后是类,然后输入,即 template <class int>

c++ templates

2
推荐指数
1
解决办法
3934
查看次数

如何编写一个模板函数,它接受一个数组和一个指定数组大小的int

对于大学练习,我被要求编写一个模板函数"print();",它带有两个参数,1:一个泛型类型的数组,2:一个指定数组大小的int.然后,该函数应将阵列中的每个项目打印到控制台.我在使用函数参数时遇到了一些麻烦.我目前的代码是:

   template <typename Type>
   Type print (Type a, Type b)
    {
        Type items;
        Type array;
        a = array;
        b = items;

        for (int i = 0; i < items; i++) {
        std::cout << std::endl << "The element of the index " << i << " is " << array << std::endl;
        std::cout << std::endl;
    }
Run Code Online (Sandbox Code Playgroud)

并在main()中:

    print(Array[], 10);
Run Code Online (Sandbox Code Playgroud)

显然将Array作为参数放置并不返回值,所以我不知道还能做什么.有任何想法吗?

c++ arrays function template-function

2
推荐指数
2
解决办法
1万
查看次数

模板的非类型参数

可能重复:
模板<unsigned int N>是什么意思?

嗨!非类型模板参数和常量是否相同?执行以下代码是否有效,因为模板参数无法修改?如果可以修改,则在声明数组"a [T]"时编译器应该抛出错误.我的理解是否正确?

template < int T > 
void foo() {  
  int a[T] ;  
}  

int main( int argc, const char* argv[] ) {  
  foo <3> () ;  
  system("pause") ;  
  return 0 ;  
}
Run Code Online (Sandbox Code Playgroud)

c++

1
推荐指数
1
解决办法
565
查看次数