c – 我们可以使用匿名结构作为模板参数吗?

c – 我们可以使用匿名结构作为模板参数吗?,第1张

概述标题很简单,但这里是一个简单的例子: #include <cstdio>template <typename T>struct MyTemplate { T member; void printMemberSize() { printf("%i\n", sizeof(T)); }};int main() { MyTemplate< 标题很简单,但这里是一个简单的例子:
#include <cstdio>template <typename T>struct MyTemplate {    T member;    voID printMemberSize() {        printf("%i\n",sizeof(T));    }};int main() {    MyTemplate<struct { int a; int b; }> t; // <-- compiler doesn't like this    t.printMemberSize();    return 0;}

当我尝试使用匿名结构作为模板参数时,编译器会抱怨.什么是最好的方式来实现这样的东西,而不必有一个单独的,命名的结构定义?

@R_404_6120@ 您不能在C 03或甚至C 0x中将未命名的类型定义为模板参数.

最好的方法是创建一个名为struct的main(在C 0x1中)

1:您不能在C 03中使用本地类型作为模板参数,但是C 0x允许.

另请查看缺陷报告here.提出的解决方案提到

The following types shall not be used as a template-argument for a template type-parameter:

a type whose name has no linkage an unnamed class or enumeration type that has no name for linkage purposes (7.1.3 [dcl.typedef]) a cv-qualifIEd version of one of the types in this List a type created by application of declarator operators to one of the types in this List a function type that uses one of the types in this List

The compiler complains when I try to use an anonymous struct as a template parameter.

你的意思是模板参数?模板参数与模板参数不同.

例如

template < typename T > // T is template parameterclass demo {};int main(){   demo <int> x; // int is template argument}
总结

以上是内存溢出为你收集整理的c – 我们可以使用匿名结构作为模板参数吗?全部内容,希望文章能够帮你解决c – 我们可以使用匿名结构作为模板参数吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1232897.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存