下面的代碼在GCC(4.9.3)和VC++(19.00.23506)中編譯得很好,但在Clang( 3.7.0)。Clang 3.7.0抱怨類不是字面的,因爲它不是一個聚合,也沒有constexpr構造函數
error: constexpr function's return type 'Foo' is not a literal type
note: 'Foo' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
代碼:rextester運行
#include <iostream>
#include <vector>
struct Foo
{
std::vector<int> m_vec;
Foo(const int *foo, std::size_t size=0):m_vec(foo, foo+size)
{;}
//Foo(const std::initializer_list<int> &init):m_vec{init}
//{;}
};
template <std::size_t N>
constexpr Foo make_fooArray(const int (&a)[N]) noexcept
{
return {a,N};
}
int main()
{
Foo f{ make_fooArray({1,2,3}) };
for (auto i : f.m_vec)
std::cout<< i <<" ";
std::cout<<std::endl;
}
代碼:
能否請你澄清這是否是一個編譯器錯誤或有我錯過了什麼? C++ 11標準是什麼意思?
這是另外一種情況,它在GCC和VC中編譯,但不在Clang中編譯。但是,如果你別名int []並明確使用它來指定initializer_list的類型,那麼它可以在所有編譯器中工作。
#include <iostream>
template <typename T, std::size_t N>
constexpr std::size_t sizeOf_fooArray(const T (&)[N]) noexcept
{
return N;
}
using intArray = int[]; //Added
int main()
{
std::cout<< sizeOf_fooArray(intArray{16,20,53,87,54,7}) <<std::endl;
}
這是輝煌!感覺就像是一個比編譯器錯誤更深的答案。我已經嘗試了你的解釋並看到了結果。 GCC中的相同代碼= http://rextester.com/OMFA48021,Clang = http://rextester.com/OYUZW55722 –