gpt4 book ai didi

使用初始化列表的 C++ 变量参数

转载 作者:行者123 更新时间:2023-12-02 10:03:16 25 4
gpt4 key购买 nike

假设以下代码是一个很小的 ​​sprintf 替代品。 (_itoa 等只是用来保持代码简短。)

#include <cstdlib>
#include <string>
class Arg {
public:
Arg(const std::string& s) :m_str(s) {}
Arg(const char* s) : m_str(s) {}
Arg(int digi, double number) {char buf[128]; m_str = _gcvt(number, digi, buf);}
operator const std::string& ()const { return m_str; }
private:
std::string m_str;
};

class Format {
public:
Format(/*const char* format, */std::initializer_list<Arg> args); // see below
const std::string& str()const { return m_str; }
private:
std::string m_str;
};

Format::Format(/*const char* format, */std::initializer_list<Arg> args) {
auto arg = args.begin();
auto format = std::string(*arg++);
for(const char* c = format.c_str(); *c!='\0'; ++c) {
if(*c=='%') { m_str+=*arg++; }
else { m_str+=*c; }
}
}


int main() {

std::string test1 = Format{"test Double:% String:%", {5, 456.78}, "foo"}.str();

// I want to make this work. See the braces.
std::string test2 = Format("test Double:% String:%", {5, 456.78}, "foo").str();

return 0;
}

你看,我想传递参数,仅限于类型“Arg”,但使用使用例如的构造函数varadic 模板而不是 initializer_list<> 以获得更好的可读性。

我试过:
    template<typename... T>
Format(T&& ... args) : Format(std::forward<Args>(args)...) {}

但我得到:
error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'Format'
note: No constructor could take the source type, or constructor overload resolution was ambiguous

最佳答案

std::initializer_list 需要 {} 而不是 ()
{5, 456.78} 没有类型,不能为模板推断。

以旧的重载方式保持语法的方法:

Format(Arg arg0) : Format(std::initializer_list{arg0});
Format(Arg arg0, Arg arg1) : Format({arg0, arg1});
Format(Arg arg0, Arg arg1, Arg arg2) : Format({arg0, arg1, arg2});
// ... Up to some limit

关于使用初始化列表的 C++ 变量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61498625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com