2016-07-27 17 views
2

Checking if a sequence container is contiguous in memory.
C++ templates that accept only certain types如果容器保證具有序列存儲

我寫一個簡單的send()方法,它在內部與C風格指針的工作原理來檢測。我希望它能夠處理所有有保證的序列容器。我的動機是雙重的:

  • 靈活的接口
  • 效率 - 使用std::array避免堆分配。

這裏是我多遠是:

template <typename Container> 
void poll(Container &out) 
{ 
    static_assert(std::is_base_of< std::array<typename Container::value_type>, Container >::value || 
        std::is_base_of< std::vector<typename Container::value_type>, Container >::value || 
        std::is_base_of< std::string<typename Container::value_type>, Container >::value, 
        "A contiguous memory container is required."); 
} 

麻煩的是,std::array需要第二個參數,而不能在編譯時是已知的。這個問題是否可以解決?可能由不同的方法?

+0

或者只是增加一個過載。 (這就是爲什麼你不能部分地專門化函數) – MSalters

回答

7

這裏正確的方法是使用特徵類。 std::is_base_of是一種特質。基本上來說:你有一個模板化的結構,它接受一個(模板)參數,並通過嵌套的類型/值返回結果。

在你的情況是這樣的

template<typename T> 
struct HasContiguousStorage: public std::false_type{}; 

template<typename T> 
struct HasContiguousStorage<std::vector<T>>: public std::true_type{}; 
// Specialize others 

正如你不應該從標準箱獲得,這已經足夠了。這也可以檢查數組:

template<typename T, size_t N> 
struct HasContiguousStorage<std::array<T,N>>: public std::true_type{}; 

在你的函數,那麼你可以重載(見enable_if)或分支上

+0

謝謝。忘了那些。 – Flamefire

6

如果容器有data()成員函數怎麼樣? (返回指針)

+0

Nah,std :: string返回'const char *'。看來我的先決條件是不真實的。 – Vorac

相關問題