我有以下 C++ 片段:
template_par<std::string> a("name", "Joh Node");
template_par<int> b("age", 23);
std::string result = templater<SomeTemplateClass>().templatize(a, b).get();
它试图为各种目的实现模板引擎。 templater
的重要部分类是:
template<class T>
class templater
{
std::map<std::string, std::string> kps;
public:
template <typename T1>
templater& templatize(template_par<T1> b)
{
kps.insert(make_pair(b.getKey(), to_string(b.getValue())));
return *this;
}
template<typename T1, typename... Args1>
templater& templatize(T1 first, Args1... args)
{
kps.insert(make_pair(first.getKey(), to_string(first.getValue())));
return templatize(args...);
}
}
即。带有可变参数的模板函数.... template_par<T>
只是基本内容的模板参数类。现在,这很有效,做得很好。
但是,我希望能够以某种方式缩短我调用 templatize
的方式。方法不仅用于美学,而且用于挑战......我认为它看起来会更好,例如:
std::string result = templater<SomeTemplateClass>().templatize(
"name" -> "Joh Node",
"age" -> 42
);
但是,由于 operator ->
,这种方法不可行作为一个有点死板的 C++ ...(std::string result = templater<SomeTemplateClass>().templatize
不是这里的重要部分,它可以隐藏在一个友好的结构中,我更担心参数的可变数量)
对于上述挑战有什么好的美化想法吗?
最佳答案
看看Boost.Assign ,特别是其中的 map 分配部分,您可以在此处选择:
std::string result = templater<SomeTemplateClass>()
("Name", "Joh Node")
("Age", 42).templatize();
我会避免比这更有创意,这会使代码变得神秘。也就是说,如果你想疯狂地尝试,你可能会喜欢我的 named operators ,这将允许语法如下:
std::string result = templater<SomeTemplateClass>().templatize(
"name" <is> "Joh Node",
"age" <is> 42
);
在这里,is
可以是任何有效的 C++ 标识符。所以不幸的是,传统的运营商已经出局了,但几乎一切都很顺利。甚至,如果您真的想要插入它,<_>
.
关于c++ - 美化变量模板化函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27229788/