C结构模板

前端之家收集整理的这篇文章主要介绍了C结构模板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用模板和结构,但它们不起作用.我搜索了很多,但我找不到解决方案.
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template<struct S>
  6. int add(S s) {
  7. return s.num + s.num2;
  8. }
  9.  
  10. int main() {
  11.  
  12. struct {
  13. int num = 10;
  14. int num2 = 20;
  15. } test;
  16.  
  17. cout << add(test) << endl;
  18. return 0;
  19. }

使用gcc时,错误是:

  1. test.cpp:5:17: error: struct S is not a valid type for a template non-type parameter
  2. test.cpp: In function int add(S)’:
  3. test.cpp:6:5: error: s has incomplete type
  4. test.cpp:5:17: error: forward declaration of struct S
  5. test.cpp: In function int main()’:
  6. test.cpp:13:19: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
  7. test.cpp:14:20: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
  8. test.cpp:17:21: error: no matching function for call to add(main()::<anonymous struct>&)’
  9. test.cpp:17:21: note: candidate is:
  10. test.cpp:6:5: note: template<<declaration error> > int add(S)
  11. test.cpp:6:5: note: template argument deduction/substitution Failed:
  12. test.cpp:17:21: note: cannot convert test (type main()::<anonymous struct>’) to type S

解决方法

您不能在此处使用关键字struct.使用class或typename(您仍然可以使用结构实例化模板).

编辑:您的其他问题与main中的匿名结构有关.不记得我头顶的规则(也许其他人可以解释它们),但这是一种非常奇怪的做事方式,所以我只提供一个工作版本:http://ideone.com/VGIogH

有点相关:Can we have an anonymous struct as template argument?

再次编辑:您最初编写的内容,主要作品中的匿名结构(在模板中替换结构后)与–std = c 11,但不是没有(即c 03).

猜你在找的C&C++相关文章