C++ can local class reference be passed to a function?

谁说胖子不能爱 提交于 2019-12-04 03:57:00

问题


I would like to know if the following is allowed:

template < class C >
void function(C&);

void function() {
  class {} local;
  function(local);
}

thanks


回答1:


It's not allowed right now. But it's supported in C++0x. The current Standard says at 14.3.1/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.

That said, if the function is also local, there's no problem

void f() {
  class L {} local;
  struct C {
    static void function(L &l) {
      // ...
    }
  };
  C::function(local);
}



回答2:


It's allowed if you use polymorphism instead of templates. Or if you don't need to extend the interface seen by function, simple inheritance will do.

void function( ABC & );

void function() {
  class special : public ABC {
      virtual void moof() {}
  } local;
  function(local);
}


来源:https://stackoverflow.com/questions/2662843/c-can-local-class-reference-be-passed-to-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!