gpt4 book ai didi

c++ - 接受const char *列表的字符串类构造函数

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

在我的String类中,我想使ctor接受可变长度的参数(const char*),例如带有可变参数模板的参数包。
像下面这样

class String
{
public:

String(const char*... xList)
{
// Internally appending all const char* present in xList and
// populating String class char buffer
}

};
任何想法如何实现这一目标?
我印象深刻的是,接下来的事情应该起作用……但是事实并非如此。
template <const char* ... Args>
String(Args... xList)
{

}
使用 va_arg可能有一种方法,但我对此并不感兴趣。

最佳答案

这是一个使用可变参数模板和SFINAE的工作示例,如果您不提供const char*,它们将不会编译

#include <type_traits>
#include <list>
#include <iostream>

struct String
{
std::list<char> ls;
template<class ... Args, class = std::enable_if_t<std::is_same_v<std::common_type_t<Args...>, const char *>>>
String(Args...args):ls{*args...}
{
}

};

int main(){
auto c1 = 'a'; const char * pc1 = &c1;
auto c2 = 'b'; const char * pc2 = &c2;
auto c3 = 'c'; const char * pc3 = &c3;
String s{pc1, pc2, pc3};

for(auto it = s.ls.begin();it != s.ls.end(); ++it)std::cout << *it;
}
Live
使用 c++11,代码可以像这样
#include <type_traits>
#include <list>
#include <iostream>

struct String
{
std::list<char> ls;

template<class ... Args, class = typename std::enable_if<std::is_same<typename std::common_type<Args...>::type, const char *>::value>::type>
String(Args...args):ls{*args...}
{
}

};

int main(){
auto c1 = 'a'; const char * pc1 = &c1;
auto c2 = 'b'; const char * pc2 = &c2;
auto c3 = 'c'; const char * pc3 = &c3;
String s{pc1, pc2, pc3};

for(auto it = s.ls.begin();it != s.ls.end(); ++it)std::cout << *it;
}
Live

关于c++ - 接受const char *列表的字符串类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63084821/

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