【发布时间】:2019-04-16 18:28:39
【问题描述】:
我想用 C++ 创建一个简单 HTML dom builder,并决定使用模板化的 tag<> 类来描述标签的类型。
我已经使用其他方法在 C++ 中创建了 DOM 并取得了一些成功,但该设计无法处理原始字符串,因此迁移到模板类可能有助于我使用模板专业化 (tag<plain>) 处理该问题。
现在的问题是使用可变参数模板将标签嵌套在其构造函数中。我已经能够使用 node 来实现它,它包含根级标签,但是任何标签内标签嵌套都是不行的。
#include <map>
#include <string>
#include <tuple>
#include <utility>
namespace web {
enum class attrs { charset, name, content, http_equiv, rel, href, id, src, lang };
using attribute = std::pair<attrs, std::string>;
using attribute_type = std::map<attrs, std::string>;
const auto none = attribute_type{};
enum tag_name { html, head, meta, title, link, body, div, script, plain, p, h1, span };
template <typename... Tags> struct node {
int increment;
std::tuple<Tags...> tags;
explicit node(const int incr, Tags... tggs)
: increment{incr}, tags{std::make_tuple(tggs...)} {}
};
template <tag_name T, typename... Tags> struct tag {
attribute_type attributes;
std::tuple<Tags...> tags;
explicit tag(attribute_type atts, Tags... tggs)
: attributes{atts.begin(), atts.end()}, tags{std::make_tuple(tggs...)} {
}
};
template <> struct tag<plain> {
std::string content;
explicit tag(std::string val) : content{std::move(val)} {}
};
} // namespace web
int main() {
using namespace web;
node page1{2};
node page2{2, tag<html>{none}};
node page3{2, tag<html>{{{attrs::lang, "en"}}}};
node page4{2, tag<meta>{{{attrs::name, "viewport"},
{attrs::content,
"width=device-width, initial-scale=1.0"}}}};
node page5{2, tag<head>{none}, tag<body>{none}, tag<plain>{"Hello World"}}; // Yet this line still compiles and works as expected...
node page6{1, tag<span>{none, tag<h1>{none}}}; // error: no matching constructor for initialization of 'tag<html>'
}
我想知道我如何能够在节点类中聚合标签,但不能在 tag 类中这样做,如果可能的话,我将能够解决这个问题。
【问题讨论】:
-
你真的想计算 html 的时间视图吗?因为您将无法读取文件内容(即“运行时”)。
-
node page6{1, tag<span, tag<h1>>{none, tag<h1>{none}}};? Demo
标签: c++ constructor c++17 variadic-templates template-argument-deduction