我们可以有一个匿名结构作为模板参数吗? [英] Can we have an anonymous struct as template argument?

查看:95
本文介绍了我们可以有一个匿名结构作为模板参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题是不言而喻的,但这里有一个简单的例子:

The title is pretty self-explanatory, but here's a simplified example:

#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;

}

编译器在我尝试使用匿名结构时模板参数。

The compiler complains when I try to use an anonymous struct as a template argument. What's the best way to achieve something like this without having to have a separate, named struct definition?

推荐答案

不允许使用一个单独的命名结构定义,在C ++ 03或甚至C ++ 0x中将未命名的类型定义为模板参数。

You are not allowed to define an unnamed type as a template argument in C++03 or even in C++0x.

最好的做法是创建一个命名的struct local main(在C ++ 0x 1

The best you can do it to create a named struct local to main (in C++0x1)

1:不允许使用本地类型作为模板参数在C ++ 03,但C ++ 0x允许它。

也检查缺陷报告在这里。建议的解决方案提到

Also check out the Defect Report here. The proposed solution mentions


以下类型不能用作模板类型参数的模板参数:

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.

您是不是指模板参数?模板参数与模板参数不同。

Did you mean template argument? Template parameter is different from template argument.

例如

template < typename T > // T is template parameter
class demo {};

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

这篇关于我们可以有一个匿名结构作为模板参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆