[英]Why the template with default template arguments can't be used as template with less template argument in Template Template Parameters
[英]Why can't a template reference type be used as a template typealias argument?
我目前正在為自定義集合樣式類編寫迭代器。 我有一個可變的迭代器類,可以很好地工作,但是我決定最好也實現一個const版本,該版本將阻止對要迭代其內容的對象的修改。 我決定避免使用單獨的類和代碼重復,方法是在網上發現使用條件輸入的建議。
我以典型的C ++ 11方式定義了iterator_traits
別名,該別名將允許代碼共享和模板參數依賴的const或可變行為(ItemType是外部容器類上的模板參數):
template<bool Const = false>
class iterator {
public:
using reference = std::conditional_t<Const, const ItemType &, ItemType &>;
using pointer = std::conditional_t<Const, const ItemType *, ItemType *>;
//Rest of the iterator_traits and some other typealiases
...
template<bool _Const = Const>
std::enable_if_t<_Const, value_type>
operator*() const
{
//Return copy
}
//Non-const version
template<bool _Const = Const>
std::enable_if_t<!_Const, reference>
operator*()
{
//Return modifiable reference type
}
...
}
我決定嘗試通過創建另一個像這樣的模板類型別名來刪除重復的std::conditional_t
調用:
template<typename type>
using const_conditional = std::conditional_t<Const, const type, type>;
並將所有std::conditional_t<...>
替換為const_conditional<some_type_here>
。 對於外部類模板參數ItemType
類型,這似乎普遍適用,但是當外部類類型的類型是引用時,則不適用於外部類類型本身,例如const_conditional<MyCollection<ItemType> &>
。 編譯后,編譯器抱怨我放棄了限定符,這意味着未應用const
,因此我違反了const要求,但是用原始的std::conditional_t
代碼替換了我的自定義類型別名,並按預期方式進行編譯和運行,我不知道為什么。
當然,我可以簡單地返回到我最初使用的std::conditional_t
調用,該調用工作正常,但它們似乎過時且重復,而且我不理解為什么我的自定義typealias失敗。 在我的特定情況下,通過互聯網進行搜索無法幫助我。 任何幫助將由衷的感謝。
ItemType&
和ItemType*
本身就是類型,因此添加const限定符將分別產生ItemType& const
(在這種情況下,由於模板參數替換而導致靜默忽略const
)和ItemType* const
,這與預期的const ItemType&
和const ItemType*
。 對於后者,您可以使用:
template <typename type>
using const_conditional = std::conditional_t<Const, const type, type>;
// ...
using reference = const_conditional<ItemType>&;
using pointer = const_conditional<ItemType>*;
附帶說明一下, _Const
是保留標識符,所有其他標識符都以下划線開頭,后跟一個大寫字母。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.