简体   繁体   English

有没有办法在gcc / g ++中强制函数解析优先级?

[英]Is there a way to force function resolution priority in gcc/g++?

It's easy to understand why we cannot say: 很容易理解为什么我们不能说:

template<class A> class foo 
{
     //stuff
     A& operator[](size_type n);
     operator A*();
     //more stuff
 };

somefooinstance[bar];

... We get back "ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for second." ...我们回过头来,“ ISO C ++表示这些模棱两可,即使第一次的最差转换比第二次的最差转换要好。”

What this means, of course, is that gcc doesn't know if we mean: 当然,这意味着gcc不知道我们的意思是:

somefooinstance.operator[](bar);

or we mean: 或者我们的意思是:

(static_cast<A*>(somefooinstance))[bar];

Now, ISO C++ says all conversions must be considered, yes? 现在,ISO C ++表示必须考虑所有转换,是吗? But is there no way to force a selection priority? 但是没有办法强制选择优先权吗? attribute doesn't seem to offer anything helpful. 属性似乎没有提供任何帮助。

(Please, no "what are you really trying to do?" answers. Yes, this is a canned example. Uncle Sam doesn't want me cutting and pasting code.) (请不要回答“您到底要做什么?”。是的,这是一个固定的示例。山姆大叔不希望我剪切和粘贴代码。)

EDIT: 编辑:

Someone wanted to see exact code: 有人想查看确切的代码:

template<class T, unsigned S> class foo
    {
    private:
        T m_bar[S];

    public:
        inline T& operator[](unsigned s)
        {
            return m_bar[s];
        }

        inline operator T*()
        {
            return m_bar; 
        }

    };

    int main(int argc, char** argv)
    {
      foo<int, 100> test;
      test[31] = 6;
    }

yields: 产量:

23 : warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: 23:警告:ISO C ++表示这些含义不明确,即使第一个的最差转换比第二个的最差转换更好:

8 : note: candidate 1: T& foo::operator[](unsigned int) [with T = int, unsigned int S = 100u] 8:注意:候选1:T&foo :: operator [](unsigned int)[with T = int,unsigned int S = 100u]

23 : note: candidate 2: operator[](int*, int) 23:注意:候选2:操作符[](int *,int)

... with no -pedantic required. ...不需要-pedantic。

Sorry about the canned example. 对不起这个罐头的例子。 What I meant by no cutting and pasting was not only can I actually not copy and paste, I can't explain what I am trying to do because rules and regulations. 我没有剪切和粘贴的意思不仅是我实际上不能复制和粘贴,而且由于规章制度我无法解释我要做什么。

In C++11 you can make the conversion operator explicit: 在C ++ 11中,您可以使转换运算符明确:

explicit operator A*();

Then it will only be used in cases like static_cast<A*>(somefooinstance) . 然后它将仅在诸如static_cast<A*>(somefooinstance)情况下使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM