简体   繁体   English

C ++中的struct模板

[英]struct templates in c++

I've learned about function templates, class templates, templates specialization but now I've came across this example which blows everything else out of the water because it's so different from the other uses I just can't understand how it was used in this example : 我已经学习了函数模板,类模板,模板专业化知识,但是现在我遇到了这个示例,它使其他所有内容无所适从,因为它与其他用法有很大不同,我只是不明白如何在此中使用它例如:

template <int n> struct Fibo
{
    static int val; 
};

template <> int Fibo<0>::val = 1;

template <> int Fibo<1>::val = 1;

template <int n> int Fibo<n>::val = Fibo<n-1>::val + Fibo<n-2>::val;

int CalcFibo(int n)
{ 
    return Fibo<n>::val;
}

Not sure I understand what was done here (of-course I can see it's fibonacci related, but the way it was used compared to class templates or function templates.. I just can't understand what's going on in here and I would be thankful if someone could help me understand) 不确定我是否了解这里所做的事情(当然,我可以看到它与斐波那契有关,但是与类模板或函数模板相比,它的使用方式也是如此。我只是不明白这里发生了什么,我会很感激如果有人可以帮助我理解)

There is no difference between struct templates and class templates, except the difference between struct s and class es themselves (ie all members in structs are public by default, and all members in classes are private by default.) struct模板和class模板之间没有区别,除了structclass es本身之间的区别(即,结构中的所有成员默认情况下都是公共的,而类中的所有成员默认情况下是私有的。)

This classic example of template metaprogramming is not specific to struct s; 模板元编程的这个经典示例并不特定于struct it can as easily be accomplished using classes as well. 使用类也可以轻松完成。 You just need a bit more typing to specify that the val member is public . 您只需要多键入一些即可指定val成员是public

As noted in the comments on your question, your code won't compile. 如您对问题的评论中所述,您的代码将无法编译。 The problem is in the CalcFibo function, where you are using a runtime value (the parameter n ) to instantiate a template, which always requires a value that is known at compile-time. 问题出在CalcFibo函数中,您在其中使用运行时值(参数n )来实例化模板,该模板始终需要在编译时已知的值。 You can change your "function" to something like this: 您可以将“功能”更改为以下形式:

template <int N> int CalcFibo () {return Fibo<N>::val;}

But I doubt that it's what you want. 但我怀疑这就是您想要的。

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

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