简体   繁体   English

为多种类型定义相同的 fmt::formatter 的最佳方法是什么?

[英]What is the best way to define the same fmt::formatter for multiple types?

I am attempting to write a custom formatter for a Vector<VType> vector.我正在尝试为Vector<VType>向量编写自定义格式化程序。 Depending on build settings, this could be a std::vector , or a __gnu_debug::vector .根据构建设置,这可能是std::vector__gnu_debug::vector Both these types present an identical external interface, and I would like to format both types identically.这两种类型都提供相同的外部接口,我想对这两种类型进行相同的格式化。 Also importantly though, only of of the type types will be properly defined at compile time.同样重要的是,只有类型类型中的一种会在编译时正确定义。

What is the proper way to achieve this?实现这一目标的正确方法是什么? I tried something along the following lines, however it did not result in creation of the formatters I needed.我尝试了以下几行,但它并没有导致创建我需要的格式化程序。

struct DataClass;

template<>
template<template<typename> typename VectorType>
struct fmt::formatter<VectorType<DataClass>> {
   //...
};

The problem is that std::vector is defined as template<class T, class Allocator = std::allocator<T>> class vector , so the lookup fails since the formatter is expecting a VectorType with only 1 template parameter.问题是 std::vector 被定义为template<class T, class Allocator = std::allocator<T>> class vector ,因此查找失败,因为格式化程序需要一个只有 1 个模板参数的VectorType One solution is to unconstrain the number of template arguments:一种解决方案是取消限制模板参数的数量:

template<>
template<template<typename...> typename VectorType>
struct fmt::formatter<VectorType<DataClass>> {
    //...
}

I would be interested in a better solution to this problem, since I could easily see this becoming a problem in the future where the formatter is now too unconstrained.我会对这个问题的更好解决方案感兴趣,因为我很容易看到这在未来成为一个问题,因为格式化程序现在太不受约束了。

You could do something like:您可以执行以下操作:

#ifdef USE_GNU_DEBUG_VECTOR
template <typename T>
using Vector = __gnu_debug::vector<T>;
#else
template <typename T>
using Vector = std::vector<T>;
#endif

template <typename T>
struct fmt::formatter<Vector<T>> {
   //...
};

where USE_GNU_DEBUG_VECTOR is controlled by your build settings.其中USE_GNU_DEBUG_VECTOR由您的构建设置控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM