数组衰减到指针和重载决议 [英] array decay to pointer and overload resolution

查看:33
本文介绍了数组衰减到指针和重载决议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

当第一个重载都可行时,您需要做出更糟糕的选择.目前它们在转化排名上并列(两者都是完全匹配"),然后由于首选非模板而打破了平局.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆