2016-04-29 41 views
1

這是代碼:Visual Studio 2015字符串文字不總是不變?

#include <iostream> 
using namespace std; 

struct ConstStr 
{ 
    char const* const Str; 
    constexpr struct ConstStr(char const* str) :Str(str) {} 
}; 

struct Container { 
    static constexpr struct ConstStr hey{ "hey" }; 
}; 


struct StructScope1 
{ 
    struct ConstStr { 
     char const* const Str; 
     constexpr ConstStr(char const* str) :Str(str) {} 
    }; 
    struct Container { 
     static constexpr StructScope1::ConstStr hey{ "hey" }; 
    }; 
}; 

struct StructScope2 
{ 
    struct Container { 
     static constexpr ConstStr hey{ "hey" }; 
    }; 
}; 

struct Container2 { 
    static constexpr struct StructScope1::ConstStr hey { "hey" }; 
}; 

int main() 
{ 
    cout << "Hello World" << endl; 
    cout << "Container::hey.Str " << Container::hey.Str << endl; 
    cout << "StructScope1::Container::hey.Str " << StructScope1::Container::hey.Str << endl; 
    cout << "StructScope2::Container::hey.Str " << StructScope2::Container::hey.Str << endl; 
    cout << "Container2::hey.Str " << Container2::hey.Str << endl; 
} 

我使用Visual Studio 2015對於一些原因,StructScope1::Container::hey聲明/初始化失敗編譯。它給出了錯誤

表達必須有一個恆定的值

但我在其他地方初始化相同的代碼,它工作得很好。這是一個編譯器錯誤,還是我錯過了什麼?

+0

「_in其他places_」 像什麼或在哪裏? –

回答

1

我認爲這是誤導性的編譯錯誤信息。

這工作:

struct StructScope1 
{ 
    struct ConstStr { 
     char const* const Str; 
     constexpr ConstStr(char const* str) :Str(str) {} 
    }; 
    struct Container; 
}; 

struct StructScope1::Container{ 
    static constexpr StructScope1::ConstStr hey{ "hey" }; 
}; 

除非我外面定義嵌套類,在構造函數之前定義的hey嘗試(構造函數必須看到標準的規則已建成hey)。

鏘是位更加清晰:

a.cpp:23:49: error: constexpr variable 'hey' must be initialized by a constant expression 
    static constexpr StructScope1::ConstStr hey{ "hey" }; 
              ^~~~~~~~~~~~ 
a.cpp:23:49: note: undefined constructor 'ConstStr' cannot be used in a constant expression 
a.cpp:20:19: note: declared here constexpr ConstStr(char const* str) :Str(str) {} 
+0

我想我明白你在說什麼。當在StructScope1中定義StructScope1 :: Container,並且在StructScope1中定義StructScope1 :: ConstStr時,則在StructScope1 :: ConstStr :: ConstStr(構造函數)之前定義StructScope1 :: Container :: hey。所以嘿試圖在定義它之前使用這個析構函數。那是對的嗎? – user1646801

+0

我的意思是構造函數,而不是析構函數。顯然,我無法編輯我的評論來解決這個問題。 – user1646801

+0

@user您可以刪除並寫入新評論。 ;;是的,那將是我的觀察。我會留下解釋爲什麼發生在一些規格專家。我的解釋是靜態成員是在構造函數之前定義的,因爲構造函數可能需要使用它們(不過,在定義時只能看到聲明);雖然它在我的VS2015上崩潰,所以可能不安全(工作正常w/clang) – krOoze