相关疑难解决方法(0)

CRTP和c ++ 1y返回类型推导

我最近在玩CRTP的时候遇到的东西让我感到惊讶,因为它与c ++ 1y函数一起使用,其类型是推导出来的.以下代码有效:

template<typename Derived>
struct Base
{
    auto foo()
    {
        return static_cast<Derived*>(this)->foo_impl();
    }
};

struct Derived:
    public Base<Derived>
{
    auto foo_impl()
        -> int
    {
        return 0;
    }
};

int main()
{
    Derived b;
    int i = b.foo();
    (void)i;
}
Run Code Online (Sandbox Code Playgroud)

我假设返回类型Base<Derived>::foodecltype返回的表达式的一个,但如果我修改这样的函数foo:

auto foo()
    -> decltype(static_cast<Derived*>(this)->foo_impl())
{
    return static_cast<Derived*>(this)->foo_impl();
}
Run Code Online (Sandbox Code Playgroud)

此代码不再起作用,我收到以下错误(来自GCC 4.8.1):

||In instantiation of 'struct Base<Derived>':|
|required from here|
|error: invalid static_cast from type 'Base<Derived>* const' to type 'Derived*'|
||In function 'int main()':|
|error: …
Run Code Online (Sandbox Code Playgroud)

c++ crtp c++11 return-type-deduction c++14

15
推荐指数
1
解决办法
1104
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

crtp ×1

return-type-deduction ×1