相关疑难解决方法(0)

decltype作为类成员函数中的返回类型

我在代码下面编译错误.

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)

那么,第一个出了什么问题?

c++ decltype c++11

12
推荐指数
2
解决办法
2164
查看次数

为什么编译器在使用decltype时不会推断出成员的类型?

我只是在自己的代码中注意到了这种行为,所以这是一个天真的问题:

这个:

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进行测试

c++ decltype language-lawyer c++11

12
推荐指数
2
解决办法
299
查看次数

放置类构造函数

为什么这段代码不正确?

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)

为什么类构造函数的位置很重要?我认为定义类构造函数的位置并不重要.

c++ constructor c++11

5
推荐指数
1
解决办法
174
查看次数

声明后使用带有成员函数定义的decltype

我使用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.是什么赋予了?

c++ c++11

4
推荐指数
1
解决办法
688
查看次数

标签 统计

c++ ×4

c++11 ×4

decltype ×2

constructor ×1

language-lawyer ×1