【问题标题】:Type deducted of method definition doesn't match declaration方法定义中扣除的类型与声明不匹配
【发布时间】:2014-10-09 22:06:15
【问题描述】:

我尝试使用 C++11/14 的一些新特性,但遇到了一个令人讨厌的事情,即在其定义中对类方法进行类型推断。

场景:

// in header foo.hpp
class MyClass {
    T foo();
}

//in source foo.cpp
auto MyClass::foo() {
    return ... //something that returns T!
}

对于 T = cl_uint (OpenCL),这不起作用,编译器输出以下错误消息:

src/device.cpp:9:7: 错误:‘auto CL::Device::addressBits() const’的原型与‘CL::Device’类中的任何内容都不匹配

src/device.hpp:31:11: 错误:候选是:cl_uint CL::Device::addressBits() const

这与最新版本的 GCC 和 Clang 的行为相同。 具体例子如下:

// in the .hpp
namespace CL {
    class Device : public Object<cl_device_id, cl_device_info, DeviceFunctions> {
    public:
        Device(cl_device_id id);

        cl_uint addressBits() const;

        // much more stuff ... (not of interest atm)
    }
}

// in the .cpp
namespace CL {
    auto Device::addressBits() const {
        return getInfo<cl_uint>(CL_DEVICE_ADDRESS_BITS);
    }
}

// in object.hpp => inherited by device
namespace CL {
    template<typename U, typename InfoIdType, typename Functions>
    class Object {
    protected:
        template<typename T>
        T getInfo(InfoIdType info_id) const {
            auto error = cl_int{CL_INVALID_VALUE};
            auto info  = T{};
            error = Functions::get_info(m_id, info_id, sizeof(T), &info, nullptr);
            return (error == CL_SUCCESS) ? info : T{};
        }
    }
}

我很清楚,这个问题不会导致任何可怕的事情,也不能通过省略这种情况的类型推断来解决。 但是,当我尝试采用新的酷炫的 C++11/14 功能时,我想了解为什么这尤其不能像我想象的那样工作。

【问题讨论】:

标签: c++ c++14 auto decltype type-deduction


【解决方案1】:

您可以将所有代码简化为:

struct A {
  int func();
};

auto A::func() { return 0; }

这是无效的,使用占位符类型声明的函数必须在所有声明中使用占位符:

[decl.spec.auto]/13:

具有使用占位符类型的已声明返回类型的函数或函数模板的重新声明或特化也应使用该占位符,而不是推导类型。

【讨论】:

    【解决方案2】:

    以下作品:

    struct MyClass {
        auto foo();
    };
    
    auto MyClass::foo() {
        return 10;
    }
    

    虽然我不知道你的案子为什么不起作用。

    (和Jonathan answer,现在我知道了)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多