Home > Enterprise >  How to forward declare a templated std::function
How to forward declare a templated std::function

Time:12-29

How do I forward declare a std function that is templated so that it could be used with various types?

namespace std{
    template<typename R, typename T>
    class function;
}

and then else where

std::function<void(int)>

Doesn't seem to work.

Edit: Switched over to using boost::function. Still can't get it to compile.

Following the suggestions,I forward declare like this in my header:

namespace boost {
    template<typename R>
    class function;
}

and use like this again in the header:

boost::function<void(int)> mIdReceiver;

Then in my source/.cpp file I include <boost/function.hpp> and initialize the field.

And I get

mIdReceiver uses undefined class boost::function<void(int)>

error.

CodePudding user response:

You are not allowed to declare or define a (primary) class template in the std namespace in the first place. It will cause the program to have undefined behavior.

This is especially true if you try to do this for a name that is already part of the standard library as is std::function. It will immediately clash with std::function's declaration.

It is surprising that you are trying to do that. There is no valid use case. If you need std::function, then you must #include <functional> and it will be declared properly without you needing to add anything to the std namespace manually.

  •  Tags:  
  • c
  • Related