【发布时间】:2021-07-08 14:10:05
【问题描述】:
我正在尝试创建一个自定义错误类,其构造函数通过将参数传递给fmt::format() 来创建错误消息。我希望它始终在编译时根据参数检查格式字符串,而不必每次抛出时都显式使用FMT_STRING()。比如:
class Err : public std::exception
{
private:
std::string m_text;
public:
template <typename S, typename... Args>
Err(const S& format, Args&&... args) {
m_text = fmt::format(FMT_STRING(format), args...);
}
virtual const char* what() const noexcept {return m_text.c_str();}
};
// ------------------------
throw Err("Error {:d}", 10); // works
throw Err("Error {:d}", "abc"); // cause Compile-time error
使用前面的代码,我在 FMT_STRING() 宏上遇到错误:
error C2326: 'Err::{ctor}::<lambda_1>::()::FMT_COMPILE_STRING::operator fmt::v7::basic_string_view<char>(void) const': function cannot access 'format'
message : see reference to function template instantiation 'Err::Err<char[11],int>(const S (&),int &&)' being compiled with [ S=char [11] ]
我对模板编程的经验很少。如何让它始终在编译时检查格式字符串,而无需每次都显式使用FMT_STRING()?
【问题讨论】:
-
comile-time 检查需要
FMT_STRING宏是有原因的。如果字符串作为常规参数传递,则可能是不可能的。
标签: c++ constexpr compile-time fmt