Why cannot refer to the embed namespace in c++

177 Views Asked by At

I got three files in one project

one is

namespace sql
{
    namespace detail
    {
        void getColumnValue();
    }
}

the other one is

namespace detail{
.........
}

the third one is

#include "first_file"
namespace sql
{
template<typename TheStruct>
    class RowStruct {

        public:
            void shouldCombine()
           {
                sql::detail::getColumnValue();          
           }
}

those three files are both in the same projects and in the same outer namespace. but then I build ,I got an error to say ":sql::detail' has not been declared " for the third file.

why I just cannot refer to the "detail" in "sql", do I miss something? If I use "detail::" in stead of "sql::detail::" in third file then it will go the the detail:: declared in second file which is not something I want.

2

There are 2 best solutions below

4
On

you have to include the first file (I assume that it's a header file) into the third file.

#include "sql_detail.h"

namespace sql
{
template<typename TheStruct>
    class RowStruct {

        public:
            void shouldCombine()
           {
                sql::detail::getColumnValue();          
           }
    };
}

and, in the second file, don't you wanted to say?:

namespace sql{
namespace detail{
//..definitions
}}
1
On

Perhaps the "outer namespace" you allude to is the problem. The way you should define this outer namespace is like this:

// file1
namespace outer {
  namespace sql {
    namespace detail { ... }
  }
}

// file3
#include "file1"

namespace outer {
  namespace sql {
    namespace detail { ... }
  }
}

If you put the #include "file1" inside the namespace outer in file3, you would get problems like you're seeing.

Also, note that if you're inside namespace sql (anywhere, including file3), you shouldn't need to explicitly say sql::detail::. Simply detail:: is sufficient from inside namespace sql to give you sql::detail::. And that's irrespective of any namespace detail definitions in other namespaces (i.e. your file2 does not change that).