Function inside a function

Normally you cannot declare a function inside another one.
But you can declare a class inside a function.
And this class can have both static and member functions.


#include <iostream>
void some_func()
{
 struct func{
  static int doit(int value) {
   return value+1;
  }
 };
 std::cout << func::doit(2) << std::endl;
}
int main()
{
 some_func();
 return 0;
}

However, there are still two problems.
First problem is that function in such nested class has no access to local function variables.
This can be solved in the following way:


#include <iostream>
void some_func()
{
        int some_data = 1;
        struct functor{
                int operator()(int value) {
                        return (m_init + value);
                }
                int m_init;
        };
        functor x = {some_data};
        std::cout << x(2) << std::endl;
}
int main()
{
        some_func();
        return 0;
}

Another bigger problem is that classes which are declared in functions don’t have external linkage.
This is a problem for C++ template since one must use classes with external linkage as template parameters.
Thus such functors are useless for STL generic algorithms.
For example the following code does not compile:


#include <iostream>
#include <vector>
#include <algorithm>
void some_func()
{
 int some_data = 1;
 struct functor{
  int operator()(int value) {
   return (m_init + value);
  }
  int m_init;
 };
 functor JobFunctor = {some_data};
 std::vector<int> vec;
 vec.push_back(1);
 vec.push_back(2);
 std::for_each(vec.begin(), vec.end(), JobFunctor);
}
int main()
{
 return 0;
}
gives you error C2918: '(void)some_func::functor' : illegal use of local type in template instantiation.

So declaring function inside another one is of very limited use.

Leave a Reply