数组衰变指针和重载解析 [英] array decay to pointer and overload resolution
本文介绍了数组衰变指针和重载解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够在重载的指针数组区分:
I want to be able to differentiate array from pointers in overload resolution :
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
}
到目前为止,我已经找到了最好是使用指针,而不是一个指针的引用:
The best I have found so far is to use a reference to the pointer instead of a pointer :
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
}
这是不完全一样的事情,我想知道是否有更好的方式存在。
it's not exactly the same thing and I want to know if a better way exist
推荐答案
您需要做的第一个重载较差的选择,当两者都是可行的。目前,他们正在转换的排名平局(均为精确匹配),然后分出胜负,因为非模板是preferred。
You need to make the first overload a poorer choice when both are viable. Currently they are a tie on conversion ranking (both are "Exact Match"), and then the tie is broken because non-templates are preferred.
这应该使转换更糟糕的排名:
This ought to make the conversion ranking worse:
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]);
};
这篇关于数组衰变指针和重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文