2016-03-15 114 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(); 
}