这是一个关于类内朋友函数的返回类型推导的小实验(std=c++1y在两种情况下都使用Clang 3.4 SVN和g ++ 4.8.1 ),链接工作文件中没有记录
#include <iostream>
struct A
{
int a_;
friend auto operator==(A const& L, A const& R)
{
return L.a_ == R.a_; // a_ is of type int, so should return bool
}
};
template<class T>
struct B
{
int b_;
friend auto operator==(B const& L, B const& R)
{
return L.b_ == R.b_; // b_ is of type int, so should return bool
}
};
using BI = B<int>;
int main() …Run Code Online (Sandbox Code Playgroud) 我最近在玩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>::foo是decltype返回的表达式的一个,但如果我修改这样的函数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)