小编Mar*_*cko的帖子

{fmt}:始终在函数中编译时检查格式字符串

我正在尝试创建一个自定义错误类,其构造函数通过将参数传递给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
Run Code Online (Sandbox Code Playgroud)

使用前面的代码,我在 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 …
Run Code Online (Sandbox Code Playgroud)

c++ compile-time constexpr fmt

2
推荐指数
1
解决办法
2502
查看次数

标签 统计

c++ ×1

compile-time ×1

constexpr ×1

fmt ×1