簡體   English   中英

C ++ CRTP名稱查找

[英]C++ CRTP Name Lookup

為什么這段代碼無法編譯(未聲明的標識符'x',g ++ 4.9和clang ++ 3.5)?

template <class T>
struct base {
    int x;
};

template <class U>
struct end : public base<U> {
    end() {
        x = 5;
    }
};

注意:明確指定this->x可以解決問題。

它不會編譯,因為在名稱查找期間會忽略依賴的基類,而base是依賴的基類。

你可以使用this指針:

end() {
    this->x = 5;
}

或者只是明確地命名基類:

end() {
    base::x = 5;
}

注意:

因為有時你可能想要使用>>作為二元運算符(右移),這不能在gcc和clang中編譯(它用MSVC 13編譯)。

簡單的辦法是增加從空間>>> >

 class end : public middle<end<U> >

這有效:

#include <iostream>

using namespace std;

class base {
public:
    int x;
};

template <class T>
class middle : public base {};

template <class U>
class end : public middle<end<U> > {
    public:
        end() {
        base::x = 5;
    }
};

int main()
{
    end<middle<base> > e;
    cout << e.x << endl; 

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM