我正在尝试为 C++ pugi xml 库编写一个通用包装器,它可以将值保存到 xml 或从 xml 存储值。
他们已经将他们的 xml 节点属性(存储为字符串)访问函数实现为函数,例如 attribute.as_int()
, attribute.as_bool()
等
我想实现与 nlohmann::json 库中相同的功能,您可以在其中调用 .get<T>()
在一些 json 对象上并获取一些类型。
我能想到的唯一方法(甚至可能行不通)是使用模板特化:
template <>
int foo<int>(xml_attribute param)
{
return param.as_int();
}
template <>
bool foo<bool>(xml_attribute param)
{
return param.as_bool();
}
等等。
这似乎导致编写的代码几乎与编写非通用包装器一样多......
最佳答案
嗯,你的方法其实还不错。我可能会坚持下去。
然而,还有另一种方式。
#include <type_traits>
template <typename T>
auto foo(xml_attribute param)
{
if constexpr (std::is_same<T, int>::value) {
return param.as_int();
}
else if constexpr (/*..*/){//...} //and so on
}
关于c++ - 如何为特定类型的访问函数编写通用模板包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621708/