2016-03-15 123 views
1

头文件我有一个工具包(具有各种公共可访问的方法的文件)内所使用的一类被称为高速缓存。缓存刷新使用回调,这需要一个函数对象。 functor对象调用Cache的函数之一,在我的工具箱中调用Cache的实例的refresh()。C++包括具名命名空间

实例是在工具箱具名命名空间内(因为我不想不必直接访问它的客户端做)。现在

,我有这一切工作,但真的想缓存有它自己的头文件,使之清楚什么方法都可以在其上。

我的问题是,我有以下几点:

// 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(); 
    } 
} 

所以我无法定义Functor::operator()()无名命名空间中,并且它也不能到外面去。

一个解决方案我也考虑过是把一大堆无名命名空间中,但是这必须包括#include为好。这是建议吗?这不是我以前真正见过的事情(这表明这可能是一个糟糕的计划......),而且我也找不到有关这种方法的优点/缺点的很多信息。

这将解决方案会是什么样子:

// toolkit.cxx 

namespace { 
    #include "cache.h" 

    Cache cache; 

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

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

可以在第二种方法的优点/缺点(尤其是缺点)任何人对此有何评论?任何其他解决方案也是值得欢迎的

+0

你应该能够实现'无效函子::运算符()()'外的匿名'namespace',使用相同的代码。这不适合你吗? –

+0

ahh是的,我不知道为什么我认为它必须在名称空间之前或在名称空间之内 - 在名称空间正常工作后实现它。谢谢! – rbennett485

+0

如果你想把它作为答案,我可以接受它 – rbennett485

回答

0

解决方案1 ​​

匿名namespace内定义Functor

#include "cache.h" 

namespace { 

    Cache cache; 

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

溶液2

匿名namespace的定义之后定义Functor

#include "cache.h" 

namespace { 

    Cache cache; 

} 

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

溶液3

匿名namespace之前声明Functor但匿名namespace的定义之后定义 Functor::operator()

#include "cache.h" 

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

namespace { 

    Cache cache; 

} 

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