我在代码下面编译错误.
struct B{
double operator()(){
return 1.0;
}
};
struct A {
auto func() -> decltype(b())
{
return b();
}
B b;
};
Run Code Online (Sandbox Code Playgroud)
但是,如果我重组A,它会编译.
gcc 4.8表示'b'未在此范围内声明.
struct A {
B b;
auto func() -> decltype(b())
{
return b();
}
};
Run Code Online (Sandbox Code Playgroud)
那么,第一个出了什么问题?
我只是在自己的代码中注意到了这种行为,所以这是一个天真的问题:
这个:
struct A
{
int get()
{
return a;
}
int a=1;
};
int main() {}
Run Code Online (Sandbox Code Playgroud)
编译当然很好,虽然当成员数据的声明谎言之后的函数定义.
但后来我不明白为什么这样:
struct A
{
auto get() -> decltype(a)
{
return a;
}
int a=1;
};
Run Code Online (Sandbox Code Playgroud)
不编译(*).我要写这个:
struct A
{
int a=1;
auto get() -> decltype(a)
{
return a;
}
};
Run Code Online (Sandbox Code Playgroud)
有什么语言相关的原因,为什么它不好,或者只是编译器没有实现它?无论类成员的顺序如何,我都希望有相同的行为.
(*)通过Ideone.com使用gcc 6.3进行测试
为什么这段代码不正确?
class Method
{
public:
Method(decltype(info2) info1);
virtual ~Method(){}
protected:
QSharedPointer<info> info2;
};
Run Code Online (Sandbox Code Playgroud)
但是这段代码是正确的:
class Method
{
public:
virtual ~Method(){}
protected:
QSharedPointer<info> info2;
public:
Method(decltype(info2) info1);
};
Run Code Online (Sandbox Code Playgroud)
为什么类构造函数的位置很重要?我认为定义类构造函数的位置并不重要.
我使用decltype作为成员函数的返回类型,但定义和声明不匹配.这是一些代码:
template<typename T>
struct A {
T x;
auto f() -> decltype(x);
};
template<typename T>
auto A<T>::f() -> decltype(x) {
return this->x;
}
int main() {}
Run Code Online (Sandbox Code Playgroud)
这产生了
test.cc:10:6: error: prototype for 'decltype (((A<T>*)0)->A<T>::x) A<T>::f()' does not match any in class 'A<T>'
test.cc:6:7: error: candidate is: decltype (((A<T>*)this)->A<T>::x) A<T>::f()
Run Code Online (Sandbox Code Playgroud)
不同之处在于定义具有(A<T>*)0声明的位置(A<T>*)this.是什么赋予了?