我正在嘗試圍繞一些決議庫(JSON、YAML 等)創建一個瘦包裝器,這將允許我使用統一的語法,而不管我使用的檔案型別/決議器。我希望包裝器利用模板,這樣我就不必在運行時進行任何動態檢查來檢查我正在使用哪個庫(這部分是學術追求)。
包裝器結構的重要部分在這里:
template<typename K> struct Wrapper
{
K node; // Element that is wrapped
Wrapper() {};
Wrapper(K impl) : node(impl) {};
Wrapper(const Wrapper<K>& other) : node(other.node) {};
const Wrapper<K> operator[](const char* key);
//... Other stuff
}
我的問題是當我嘗試將多個[]操作鏈接在一起時遇到編譯時錯誤。
該operator[]過載可以在這里找到:
// Returning by value since I am creating an object that goes out of scope.
// This is okay because the parsing is read only.
template<> const Wrapper<to_wrap> Wrapper<to_wrap>::operator[](const char* key)
{
// It is safe to assume that node[key] produces a to_wrap type.
return Wrapper<to_wrap>(node[key]);
}
通過一些示例說明如何呼叫它:
template<typename T> bool configure(T config)
{
?Wrapper<T> root(config);
// Method A
?Wrapper<T> thing = root["field1"]["field2"];
// Method B
?Wrapper<T> first_thing = root["field1"];
?Wrapper<T> second_thing = first_thing["field2"];
}
如果我嘗試Method A. Method B產生我在編譯和運行時期望的結果:一個Wrapper包含適當的node. 錯誤A如下:
error: conversion from ‘const char’ to non-scalar type ‘Wrapper<to_wrap>’ requested Wrapper<T> thing = root["field1"]["field2"];
這讓我認為編譯器如何推斷型別存在問題,但我并不完全確定。任何幫助/見解將不勝感激!
uj5u.com熱心網友回復:
改變
const Wrapper<K> operator[](const char* key);
到
const Wrapper<K> operator[](const char* key) const;
或者 - 更好的是 - 制作operator[].
Wrapper<K> operator[](const char* key);
const Wrapper<K> operator[](const char* key) const;
您的當前operator[]回傳一個const物件,并且不允許在const物件上使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380306.html
上一篇:使用可變引數模板列印類物件
