【发布时间】: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