Passing unnamed classes through functions

后端 未结 4 871
-上瘾入骨i
-上瘾入骨i 2020-12-11 20:22

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

4条回答
  •  -上瘾入骨i
    2020-12-11 20:54

    Why should you create an anonymous class when you want to pass it to a function?

    Just explicitly declare the class:

    class Foo {
      // ...
    };
    
    void Method(Foo instance); 
    
    int main() {
        Foo bar;
        Method(bar);
    }
    

    The 2nd possibility would be using a template-function, so the compiler would infer the type (Note that this is not standard-compatible!)

    #include 
    
    using namespace std;
    
    template 
    void SayFoo(T& arg) {
        arg.Foo();
    }
    
    int main() {
    
        class {
        public: 
            void Foo() { cout << "Hi" << endl; }
        } Bar;
    
        Bar.Foo();
    
        SayFoo(Bar);
    
        return 0;
    }
    

    There is no problem with copying the class since the compiler generated the copy constructor automatically and you can use tools like boost::typeof in order to avoid referring to the type explicitly.

    BOOST::AUTO(copy, Bar);
    

    Another approch is using (relatively slow) runtime-polymorphism (interfaces/inheritance).

提交回复
热议问题