2011-12-16 47 views
0

我有一個單身類是多數民衆贊成我的主要引擎。最好的方法來創建一個模板方法(對於單例類),接收模板類作爲參數

因爲即時通訊使用D3D11,它使用相同的ID3D11Device方法來創建所有緩衝區(無論類型),我試圖創建一個模板方法來創建緩衝區。

還我作爲源緩衝用的是一個std ::陣列

等什麼即時試圖至今:

template <size_t Size, typename T> 
void CreateBuffer(BufferType bufferType, const std::array <T, Size>& source, ID3D11Buffer** out) { 
    (...) 
    bd.BindFlags = bufferType; 
    bd.ByteWidth = sizeof(T) * source.size(); 
    (...) 
} 

,然後我用它喜歡:

ID3D11Buffer* buffer = nullptr; 
array <SimpleVertex, 10> data; //this is the source data, 10 simple vertices 
D3DEngine::GetInstance().CreateBuffer <10> (D3DEngine::Vertex, data, &buffer); 

這個工程,但看起來很醜。作爲參數模板的「10」強制我「硬編碼」的大小(我甚至不能使用<data.size()>,因爲它需要一個常量作爲模板參數)。

有沒有更好的方法來實現我想要的?或者我應該使用不同的方法? 謝謝。

+1

CreateBuffer(D3DEngine ::頂點,數據,和緩衝液)要細。你的編譯器是什麼? – Shawnone 2011-12-16 16:45:52

+0

VS 2010,它確實編譯,但在調用.CreateBuffer() – sap 2011-12-16 16:49:15

回答

1

編譯器應該能夠推斷大小和類型參數。

爲什麼你的引擎是單身人士?這點沒什麼意義。你可以返回指針,而不是指向它。而不是資源管理指針?很高興我不維護你的代碼。

0

我做了一個快速的test-case它似乎工作沒有手動指定數組的大小。

這是代碼:

#include <iostream> 
#include <string> 
#include <array> 

template<size_t S, typename T> size_t CreateBuffer(std::string const & s, std::array<T, S> const & source) 
{ 
    // do something 
    return S; 
} 

int main(int argc, char ** argv) 
{ 
    std::array<std::string, 10> arr; 
    size_t ret = CreateBuffer("my string", arr); 
    std::cout<<"Size: "<<ret; 
    return 0; 
} 
相關問題