4

Below is some simplified code from a header file in which the free functions are declared but not defined and the vector is both declared and defined.

The cpp file contains the implementation of the free functions.

I was wondering if there was a way to declare the vector in the header file and put the definition in the cpp file.

// my-file.h

namespace MyNamespace
{
    bool foo(const std::string& name, const std::string& value);
    void bar(const std::string& name, const std::string& value);

    const std::vector<std::function<void(const std::string&, const std::string&)>> m_myVector
    {
        foo,
        bar,
        [](const std::string& name, const std::string& value)
        {
            // do some stuff
        }
    };

} // MyNamespace
ksl
  • 3,901
  • 7
  • 50
  • 100
  • If you move out the code accessing the vector to a separate translation unit, you can use a forward declaration: `template std:vector;`. – πάντα ῥεῖ Jul 16 '15 at 11:07
  • 1
    I am not seeing the vector in the code. Are you looking for [extern](http://stackoverflow.com/questions/10422034/when-to-use-extern-in-c) std::vector? – nwp Jul 16 '15 at 11:08
  • 1
    Don't use a name like `m_myvector` for non-member variables, you will confuse people reading your code because the `m_` prefix conventionally means a member. – Jonathan Wakely Jul 16 '15 at 12:08

1 Answers1

5

You may declare const variable in your header as:

extern
const std::vector<std::function<void(const std::string&, const std::string&)>> m_myVector;
Jarod42
  • 173,454
  • 13
  • 146
  • 250