【发布时间】:2021-07-15 18:05:36
【问题描述】:
我有一个简单的类,它有一个 tostring() 方法:
class MyClass {
public:
std::string tostring() const;
static iterator begin();
static iterator end();
};
虽然我现在使用的是 fmt 库,但这段代码是从没有使用的代码中移植过来的,所以很多遗留类都实现了 tostring() 方法,而且我有一个模板可以生成 fmt::formatter任何具有该方法的类。它运行良好。
然而,这个特定的类也有开始/结束功能。但是它们是静态的(此类类似于枚举,您可以遍历所有可能的值),并且与格式无关。
在我需要为一些不同的代码包含 fmt/ranges.h 之前,一切都很好。问题是有一个范围格式化程序可以看到开始/结束函数并希望将类格式化为范围。现在,如果我尝试格式化该类,我会得到一个模棱两可的格式化程序实例(一个用于我要使用的模板,一个用于范围格式化程序)。
有没有办法让范围格式化程序忽略这个类?
一个完整的例子是:
#include <type_traits>
#include <utility>
#include <string>
#include <vector>
#include <fmt/format.h>
// #include <fmt/ranges.h>
// Create formatter for any class that has a tostring() method
template <typename T>
struct has_tostring_member {
private:
template <typename U>
static std::true_type test( decltype(&U::tostring) );
template <typename U>
static std::false_type test(...);
public:
using result = decltype(test<T>(0) );
static constexpr bool value = result::value;
};
template <typename T, typename Char>
struct fmt::formatter<T, Char,
std::enable_if_t<has_tostring_member<T>::value > >
: formatter<basic_string_view<Char>, Char> {
template <typename FormatContext>
auto
format( const T& e, FormatContext& ctx )
{
return formatter<string_view>::format( e.tostring(), ctx );
}
};
class MyClass
{
public:
explicit MyClass(int i) : value(i) {}
std::string tostring() const { return std::to_string(value); }
static auto begin() { return std::begin(static_data); }
static auto end() { return std::end(static_data); }
private:
int value;
static const std::vector<std::string> static_data;
};
const std::vector<std::string> MyClass::static_data{ "a", "b", "c" };
int main(void) {
MyClass c{10};
fmt::print("c is {}\n", c);
return 0;
}
如果我对 MyClass 使用 fmt::formatter 的完全专业化,那么就没有歧义,但是如果我像示例中那样使用部分专业化,那么取消注释“#include
【问题讨论】:
-
也就是说,创建minimal reproducible example