通过函数传递未命名的类 [英] Passing unnamed classes through functions

查看:97
本文介绍了通过函数传递未命名的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将此实例作为参数传递给函数?

  class 
{
public:
void foo();
} bar;

我必须为课程命名吗?

没有将类的副本转换为私有。

所以,如果有的话,怎么可能呢?

解决方案

p>也许这将是更好,如果你明确你想做什么。为什么要创建一个未命名的类?它是否符合接口?未命名的类是相当有限的,它们不能用作函数的参数,它们不能用作模板类型参数...

现在如果你要插入一个接口您可以传递对该接口的引用:

  class interface {
public:
virtual void f const = 0;
};
void function(interface const& o)
{
o.f();
}
int main()
{
class:public interface {
public:
virtual void f()const {
std: :cout< bar< std :: endl;
}
} bar;
function(bar); // will printtoutbar
}

注意:参数作为选项,未命名的类不能作为模板类型参数传递。



C ++标准。 14.3.1,第2段:


2本地类型,没有
链接的类型,未命名类型或类型
从这些类型中复合而来的
不能用作模板
类型参数的
模板参数。


如果您使用 comeau 编译器测试(链接为在线试用),您会得到以下错误:


错误:模板参数不能
引用未命名类型


另外,comeau编译器是我知道的最标准的兼容编译器,除了具有最有用的错误诊断的编译器尝试。



注意:Comeau和gcc(g ++ 4.0)给出上面的代码错误。英特尔编译器(以及其他人的评论MSVS 2008)接受使用未命名的类作为模板参数,对照标准。


How do I pass this instance as a parameter into a function?

class
{
    public:
    void foo();
} bar;

Do I have to name the class?
It is copyable since I haven't made the class's copy ctor private.
So how is it possible if at all?

解决方案

Maybe it would be better if you explicit what you want to do. Why do you want to create an unnamed class? Does it conform to an interface? Unnamed classes are quite limited, they cannot be used as parameters to functions, they cannot be used as template type-parameters...

Now if you are implmenting an interface then you can pass references to that interface:

class interface {
public:
   virtual void f() const = 0;
};
void function( interface const& o )
{
   o.f();
}
int main()
{
   class : public interface {
   public:
      virtual void f() const {
         std::cout << "bar" << std::endl;
      }
   } bar;
   function( bar ); // will printout "bar"
}

NOTE: For all those answers that consider template arguments as an option, unnamed classes cannot be passed as template type arguments.

C++ Standard. 14.3.1, paragraph 2:

2 A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

If you test with comeau compiler (the link is for the online tryout) you will get the following error:

error: a template argument may not reference an unnamed type

As a side note, comeau compiler is the most standard compliant compiler I know of, besides being the one with the most helpful error diagnostics I have tried.

NOTE: Comeau and gcc (g++ 4.0) give an error with the code above. Intel compiler (and from other peoples comments MSVS 2008) accept using unnamed classes as template parameters, against the standard.

这篇关于通过函数传递未命名的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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