2016-04-06 53 views
0

我正在寫一個容器模板的實例,聲明來自同一類型的變量作爲模板

template <typename T, typename S> 
class Container 
{ 
    public: 
     S size(void) const { return mItems; } 

    private: 
     S mItems; 
     S mMaxItems; 
     T *mArray; 
}; 

而在代碼中,我想這樣做:

Container<Rooms, int> RoomCtr; 

for(RoomCtr::type i = 0; i < RoomCtr.size(); i++) 
{ 
} 

所以該變量與S類型匹配,沒有指定int硬編碼。

這可能嗎?

我迄今發現的唯一方法是這樣的:

template <typename T, typename S> 
class Container 
{ 
    S type(void) const { return 0; } 
    ... 
}; 


for(decltype(Table.type()) i = 0; i < RoomCtr.size(); i++) 
{ 
} 

我不知道是否有更好的方法。或者這是否是正確的方法?

我目前使用Visual Studio 2010中

+0

什麼是'Rooms'?容器的大小? – ForceBru

+0

請注意,如果'type()'函數僅用於未評估的上下文中,則不需要定義,因爲「decltype」的操作數是。 – Quentin

+0

是的,你需要使用decltype。或者像你一樣,或者如果'Container'包含'typedef S Type;'作爲'decltype(Table):: Type'。這可能是最接近內省的。 – Peter

回答

0

使用的typedef:

// Example program 
#include <iostream> 
#include <string> 
template <typename T, typename S> 
class Container 
{ 
    public: 
     typedef S SomeType; 
     S size(void) const { return mItems; } 

    private: 
     S mItems; 
     S mMaxItems; 
}; 

struct A 
{ 
    //empty 
}; 
int main() 
{ 
    Container<A, int> roomCtr; 
    decltype(roomCtr)::SomeType j = 0; 
    std::cout << j << std::endl; 
} 
+0

這個工作(即使它不適用於VS2010,但這是一個不同的問題:))。 – Devolus

2

你可以做一個簡單的typedef

template <typename T, typename S> 
class Container { 
    T *data; 
    /* other variables */ 

    public: 
    typedef S size_type; 
    Container(); 

}; 

int main() { 
    Container<char, int>::size_type something; 
} 

這裏somethingint類型。

+0

這並沒有回答這個問題,因爲這裏沒有使用現有的變量實例。相反,我必須重新輸入完​​整的模板定義,我將避免使用decltype。此外,如果我決定將int更改爲short,那麼'something'將是錯誤的類型。因爲它不與實例關聯。 – Devolus

+0

@Devolus在這種情況下,只是在執行'decltype(RoomCtr):: size_type'有什麼問題? – TartanLlama

+1

嗯,這是['std :: vector'](http://www.cplusplus.com/reference/vector/vector/)如何做到的。另外,如果你想使用現有的實例,你需要一個成員函數,返回一個類型,而不是這個類型的實例,這是不可能的,據我所知。 – ForceBru

0

你可以使用typedefs來解決你的問題。 例如: -

// Example program 
#include <iostream> 
#include <string> 


template <typename T, typename S> 
class Container 
{ 
    public: 
     S size(void) const { return mItems; } 

    private: 
     S mItems; 
     S mMaxItems; 
}; 

struct A 
{ 
    //empty 
}; 
int main() 
{ 
    typedef int SomeType; 
    Container<A, SomeType> RoomCtr; 

    for(SomeType i = 0; i < 10; i++) 
     std::cout << i << std::endl; 

} 

你也可以明確地保持類型的類與一個typedef。 例如爲:與decltype組合

// Example program 
#include <iostream> 
#include <string> 
template <typename T, typename S> 
class Container 
{ 
    public: 
     typedef S SomeType; 
     S size(void) const { return mItems; } 

    private: 
     S mItems; 
     S mMaxItems; 
}; 

struct A 
{ 
    //empty 
}; 
int main() 
{ 
    typedef int MyType; 
    Container<A, MyType> roomCtr; 
    Container<A, MyType>::SomeType j = 0; 
    std::cout << j << std::endl; 

} 
+0

與其他答案中的問題相同。它不會從實例變量中推斷出類型。 – Devolus

相關問題