【问题标题】:Is there a way to force function resolution priority in gcc/g++?有没有办法在 gcc/g++ 中强制函数解析优先级?
【发布时间】:2013-02-21 00:08:42
【问题描述】:

很容易理解为什么我们不能说:

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

somefooinstance[bar];

...我们回来了“ISO C++ 说这些是模棱两可的,即使第一个的最差转换比第二个的最差转换更好。”

当然,这意味着 gcc 不知道我们的意思:

somefooinstance.operator[](bar);

或者我们的意思是:

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

现在,ISO C++ 说必须考虑所有转换,是吗?但是有没有办法强制选择优先级? 属性 似乎没有提供任何帮助。

(请不要回答“你真正想做什么?”。是的,这是一个固定的例子。山姆大叔不想让我剪切和粘贴代码。)

编辑:

有人想查看确切的代码:

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;
    }

产量:

23 : 警告:ISO C++ 说这些是模棱两可的,尽管第一个的最差转换比第二个的最差转换更好:

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

23 : 注意: 候选 2: operator[](int*, int)

... 不需要 -pedantic。

对罐头示例感到抱歉。我所说的不剪切和粘贴的意思不仅是我实际上不能复制和粘贴,我无法解释我想要做什么,因为规则和规定。

【问题讨论】:

  • 无法剪切和粘贴代码不能作为发布无法证明您所指错误的内容的借口,如果您可以在 SO 上发布,您可以在 ideone.com 在线测试代码、gcc.godbolt.org、liveworkspace.org 等 -- 我认为诊断仅来自 -pedantic
  • @JonathanWakely 不需要 -pedantic。见编辑。
  • 这只是一个警告,所以 GCC 确实 知道该选择哪个。但我无法重现该警告,您使用的是哪个版本?

标签: c++ templates gcc casting operator-overloading


【解决方案1】:

在 C++11 中,您可以明确转换运算符:

explicit operator A*();

那么它只会在static_cast&lt;A*&gt;(somefooinstance)这样的情况下使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多