加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:51:08 所属栏目:百科 来源:网络整理
导读:标题很简单,但这里是一个简单的例子: #include cstdiotemplate typename Tstruct MyTemplate { T member; void printMemberSize() { printf("%in",sizeof(T)); }};int main() { MyTemplatestruct { int a; int b; } t; // -- compiler doesn't like this t
标题很简单,但这里是一个简单的例子:
#include <cstdio>

template <typename T>
struct MyTemplate {

    T member;

    void printMemberSize() {
        printf("%in",sizeof(T));
    }

};

int main() {

    MyTemplate<struct { int a; int b; }> t; // <-- compiler doesn't like this

    t.printMemberSize();

    return 0;

}

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

解决方法

您不能在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 parameter
class demo {};

int main()
{
   demo <int> x; // int is template argument
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读