gpt4 book ai didi

c++ - 数组衰减到指针和重载解析

转载 作者:可可西里 更新时间:2023-11-01 15:41:06 29 4
gpt4 key购买 nike

我希望能够在重载决策中区分数组和指针:

class string {
public:
string(const char* c_str);

template<int N>
string(const char (&str) [N]);
};


int main() {
const char* c_str = "foo";
string foo(c_str); // ok will call string(const char*)

string bar("bar"); // call string(const char*) instead of the array version
}

到目前为止我发现的最好的方法是使用对指针的引用而不是指针:

class string {
public:
string(const char*& c_str);

template<int N>
string(const char (&str) [N]);
};


int main() {
const char* c_str = "foo";
string foo(c_str); // ok will call string(const char*)
string bar("bar"); // ok, will call the array version
}

这不完全一样,我想知道是否存在更好的方法

最佳答案

当两者都可行时,您需要让第一个重载成为一个较差的选择。目前它们在转化率排名上并列(均为“完全匹配”),但后来因为首选非模板而打破了并列。

这应该会使转化排名变差:

struct stg
{
struct cvt { const char* p; cvt(const char* p_p) : p(p_p) {} };

// matches const char*, but disfavored in overload ranking
stg(cvt c_str); // use c_str.p inside :( Or add an implicit conversion

template<int N>
stg(const char (&str) [N]);
};

关于c++ - 数组衰减到指针和重载解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21972652/

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