如何实现constexpr std::string_view与数字的乘法操作?
问题:实现std::string_view与数字相乘的功能(类似Python的
"{}"*8) 需求
想要实现类似Python中"{}"*8的功能,让std::string_view与数字相乘,以此简化fmt::format格式字符串中{}的重复书写。
编写的代码
inline constexpr auto operator*(const std::string_view& sv, size_t times) -> std::array<char, sv.length() * times> { std::array<char, sv.length() * times> result; constexpr char* data = result.data(); for(int i=0; i<times; ++i){ for(int j=0; j<sv.length(); ++j, ++data){ *data = sv.data()[j]; } } return result; }
编译器错误信息
/home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:114: error: template argument 2 is invalid 96 | inline constexpr auto operator*(const std::string_view& sv, size_t times) -> std::array<char, sv.length() * times> { | ^ /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:114: error: template argument 2 is invalid /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:114: error: template argument 2 is invalid /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:114: error: template argument 2 is invalid /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:78: error: invalid template-id 96 | inline constexpr auto operator*(const std::string_view& sv, size_t times) -> std::array<char, sv.length() * times> { | ^~~ /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:97: error: use of parameter outside function body before ‘.’ token 96 | inline constexpr auto operator*(const std::string_view& sv, size_t times) -> std::array<char, sv.length() * times> { | ^ /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:114: error: use of parameter outside function body before ‘>’ token 96 | inline constexpr auto operator*(const std::string_view& sv, size_t times) -> std::array<char, sv.length() * times> { | ^ /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:96:23: error: deduced class type ‘array’ in function return type 96 | inline constexpr auto operator*(const std::string_view& sv, size_t times) -> std::array<char, sv.length() * times> { | ^~~~~~~~ In file included from /usr/include/c++/11/tuple:39, from /usr/include/c++/11/bits/unique_ptr.h:37, from /usr/include/c++/11/memory:76, from /home/miki/dumpefs_cpp/spdlog-1.11.0/include/spdlog/fmt/bundled/format.h:40, from /home/miki/dumpefs_cpp/spdlog-1.11.0/include/spdlog/fmt/bundled/compile.h:11, from /home/miki/dumpefs_cpp/include/fs/f3s_spec.h:23, from /home/miki/dumpefs_cpp/src/dumpefs.cpp:15: /usr/include/c++/11/array:95:12: note: ‘template<class _Tp, long unsigned int _Nm> struct std::array’ declared here 95 | struct array | ^~~~~
疑问
- constexpr环境下似乎不能使用char指针,那该如何完成字符复制?
- 函数返回类型
std::array<char, sv.length() * times>中的参数都是const属性,为什么模板参数2不被允许?
编译器信息
- C++编译器路径:
/usr/bin/g++11 - C++编译器版本:11.3.0
- C++编译选项:
-fdiagnostics-color=always -g -O0
内容的提问来源于stack exchange,提问作者MikimotoH
相关产品推荐
相关产品推荐

