c++ – Declaring classes inside functions

Question:

Can I declare classes inside functions? How about passing objects created in this way to other functions? For example, this code is executed as intended:

#include <iostream>

template <typename T>
void foo (T x)
{
    std::cout << x.a;
}

int main() {
    struct X {
        int a = 3;
    } x;

    foo(x);
}

Answer:

In a similar question on the English-language StackOverflow , they answer that you can declare local classes and structures. However, before C ++ 11, they could not be used as template parameters, but you can, for example, to implement a factory (the example from this answer is correct in C ++ 03):

// В .h
class Base
{
public:
    virtual ~Base() {}
    virtual void DoStuff() = 0;
};

Base* CreateBase( const Param& );

// В .cpp
Base* CreateBase( const Params& p )
{
    struct Impl: Base
    {
        virtual void DoStuff() { ... }
    };

    ...
    return new Impl;
}

Starting with C ++ 11, they can be used as template parameters, that is, with C ++ 11 your example is also correct.

Scroll to Top
AllEscort