4

I would like to know if the following is allowed:

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

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

thanks

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
Anycorn
  • 50,217
  • 42
  • 167
  • 261

2 Answers2

6

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);
}
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • bummers. Is there clean alternative for named tuples (which is what been trying to do)? – Anycorn Apr 18 '10 at 15:59
  • Ah. I think local function will do it for me. Thanks – Anycorn Apr 18 '10 at 16:05
  • You mean `class { int a; int b; } x; function(x);` ? Not possible: the type of `x` is local. You have to go your way with pair, or make x's class not local (the variable `x` can still be local). Put the class into an unnamed namespace for example. I usually consider functions inside local classes like this a bit hacky :) But i'm glad i could be of help. – Johannes Schaub - litb Apr 18 '10 at 16:07
0

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);
}
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421