Dec*_*ade 1 c++ gcc templates type-inference
我正在尝试围绕一些解析库(JSON、YAML 等)创建一个薄包装器,这将允许我使用统一的语法,而不管我使用的文件类型/解析器如何。我希望包装器利用模板,这样我就不必在运行时进行任何动态检查来检查我正在使用哪个库(这部分是学术追求)。
\n包装器结构的重要部分在这里:
\ntemplate<typename K> struct Wrapper\n{\n K node; // Element that is wrapped\n\n Wrapper() {};\n Wrapper(K impl) : node(impl) {};\n Wrapper(const Wrapper<K>& other) : node(other.node) {};\n\n const Wrapper<K> operator[](const char* key);\n \n //... Other stuff\n}\nRun Code Online (Sandbox Code Playgroud)\n我的问题是,当我尝试将多个[]操作链接在一起时遇到编译时错误。
超载operator[]可以在这里找到:
// Returning by value since I am creating an object that goes out of scope.\n// This is okay because the parsing is read only.\ntemplate<> const Wrapper<to_wrap> Wrapper<to_wrap>::operator[](const char* key)\n{\n // It is safe to assume that node[key] produces a to_wrap type.\n return Wrapper<to_wrap>(node[key]);\n}\nRun Code Online (Sandbox Code Playgroud)\n举一些如何调用它的例子:
\ntemplate<typename T> bool configure(T config)\n{\n \xe2\x80\x8bWrapper<T> root(config);\n\n // Method A\n \xe2\x80\x8bWrapper<T> thing = root["field1"]["field2"];\n\n // Method B\n \xe2\x80\x8bWrapper<T> first_thing = root["field1"];\n \xe2\x80\x8bWrapper<T> second_thing = first_thing["field2"];\n}\nRun Code Online (Sandbox Code Playgroud)\n如果我尝试,则会发生编译时错误Method A。Method B产生我在编译和运行时期望的结果:一个Wrapper包含适当的node. 错误A如下:
error: conversion from \xe2\x80\x98const char\xe2\x80\x99 to non-scalar type \xe2\x80\x98Wrapper<to_wrap>\xe2\x80\x99 requested Wrapper<T> thing = root["field1"]["field2"];\nRun Code Online (Sandbox Code Playgroud)\n这让我认为编译器如何推断类型存在问题,但我并不完全确定。任何帮助/见解将不胜感激!
\n改变
const Wrapper<K> operator[](const char* key);
Run Code Online (Sandbox Code Playgroud)
到
const Wrapper<K> operator[](const char* key) const;
Run Code Online (Sandbox Code Playgroud)
或者 - 更好 - 制作 const 和非 const 版本的operator[].
Wrapper<K> operator[](const char* key);
const Wrapper<K> operator[](const char* key) const;
Run Code Online (Sandbox Code Playgroud)
您的当前operator[]返回一个const对象,并且不允许在const对象上使用。