Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

c++ - Passing unnamed classes through functions

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...