简体   繁体   中英

c++ including header file in unnamed namespace

I have a class called Cache used within a toolkit (a file with various publicly accessible methods). Cache is refreshed using a callback, which requires a functor object. The functor object calls one of Cache's functions, refresh() on the instance of Cache in my toolkit.

The instance is within an unnamed namespace in the toolkit (since I don't want clients having direct access to it).

Now, I had this all working, but would really like Cache to have its own header file to make it clear what methods are available on it.

My problem is that I have the following:

// toolkit.cxx
#include "cache.h"

// Can't define operator()() here since it needs access the to cache instance
struct Functor {
   void operator() ();
};

// Define Cache's fucntions here (including use of Functor)

namespace {
   Cache cache;

// This gives a compiler error - definition of operator Functor::()() is not in namespace enclosing 'Functor'
   void Functor::operator() () {
      cache.refresh();
   }
}

So I can't define Functor::operator()() inside the unnamed namespace, and it can't go outside either.

One solution I have considered is to bring the whole lot inside the unnamed namespace, but this would have to include the #include as well. Is this recommended? It's not something I have really seen done before (which suggests it may be a bad plan...), and I couldn't find much information on the pros/cons of such an approach.

This would solution would look like:

// toolkit.cxx

namespace {
   #include "cache.h"

   Cache cache;

   struct Functor {
     void operator()() {
        cache.refresh();
   };

  // Define Cache's fucntions here (including use of Functor)
}

Could anyone comment on the pros/cons (especially cons) of this second approach? Any alternative solutions would also be welcome

Solution 1

Define Functor within the anonymous namespace .

#include "cache.h"

namespace {

   Cache cache;

   struct Functor {
      void operator() () {
         cache.refresh();
      }
   };
}

Solution 2

Define Functor after the definition of the anonymous namespace .

#include "cache.h"

namespace {

   Cache cache;

}

struct Functor {
   void operator() () {
      cache.refresh();
   }
};

Solution 3

Declare Functor before the anonymous namespace but define Functor::operator() after the definition of the anonymous namespace .

#include "cache.h"

struct Functor {
   void operator() ();
};

namespace {

   Cache cache;

}

void Functor::operator() () {
   cache.refresh();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM