C++ 在C+中使用constexpr和auto的声明冲突+;11
我正在试验C++11、constexpr和auto 我无法理解为什么这段代码不能编译:C++ 在C+中使用constexpr和auto的声明冲突+;11,c++,templates,gcc,constexpr,auto,C++,Templates,Gcc,Constexpr,Auto,我正在试验C++11、constexpr和auto 我无法理解为什么这段代码不能编译: template<class T, T t> struct TestEle2 { }; template<class T, T t> struct DStruct {int a;}; template<char t> struct TestEle2<char, t> { static constexpr
template<class T, T t>
struct TestEle2
{
};
template<class T, T t>
struct DStruct {int a;};
template<char t>
struct TestEle2<char, t>
{
static constexpr auto f = 5;
static constexpr auto g = &DStruct<char, t>::a;
};
template<char c>
constexpr decltype(TestEle2<char, c>::f)
TestEle2<char, c>::f ; // This compiles
template<char c>
constexpr decltype(TestEle2<char, c>::g)
TestEle2<char, c>::g ; // This does not compile
模板
结构测试2
{
};
模板
结构数据结构{int a;};
模板
结构测试2
{
静态constexpr auto f=5;
静态constrexpr auto g=&DStruct::a;
};
模板
constexpr decltype(TestEle2::f)
测试对象2::f;//这就编译了
模板
constexpr decltype(TestEle2::g)
TestEle2::g;//这是不可编译的
没有定义,我有链接问题。我知道这个问题在C++17中已经解决了,但是现在更好地理解C++11了
[编辑]
错误消息是:
error: conflicting declaration ‘constexpr decltype (TestEle2<char, t>::g) TestEle2<char, t>::g’
TestEle2<char, c>::g ;
^
error: ‘TestEle2<char, t>::g’ has a previous declaration as ‘constexpr const auto TestEle2<char, t>::g’
static constexpr auto g = &DStruct<char, t>::a;
^
error: declaration of ‘constexpr const auto TestEle2<char, t>::g’ outside of class is not definition [-fpermissive]
错误:声明“constexpr decltype(TestEle2::g)TestEle2::g”冲突
睾丸2::g;
^
错误:“TestEle2::g”以前的声明为“constexpr const auto TestEle2::g”
静态constrexpr auto g=&DStruct::a;
^
错误:类外的“constexpr const auto TestEle2::g”声明不是定义[-fpermissive]
[编辑2]
我使用的是GCC4.8.5请考虑下面的长篇评论,而不是回答(对不起) 我不知道谁是对的(MSV接受所有,g++接受
f
但拒绝g
,或clang++拒绝f
和g
),但是,如果我理解正确,这是一个更复杂问题的简化,您不能简单地使用int
和int*
而不是auto
来解决这个问题
因此,我建议在TestEle2
using typeF = decltype(5);
using typeG = decltype(&DStruct<char, t>::a);
当编译失败时,通常会出现一条诊断消息。你没有得到任何信息吗?首先,你有一个输入错误,应该是
::g
,而不是::f
。元组也是一个麻烦,你能删除所有不需要的代码吗?这与DStruct
的模板方面有关。不知道为什么。Clang在这两种情况下都失败了,gcc只在第二种情况下工作(MSVC不关心…)非常好的解决方案,我将研究它。谢谢你的反馈@斯沃特伦-但不是你问题的答案;我怀疑你有一个鸡蛋和鸡的问题,我不是一个语言律师,所以我不知道哪个编译器是正确的。但是在定义之前,使用或typedef
,类型应该解决鸡蛋和鸡的问题。我认为你是对的。如果它真的是一个GCC错误,我需要一个解决方案,而你提出的那个似乎是一个很好的解决方案。唯一相反的是我认为代码重复
template <class T, T t>
struct TestEle2
{ };
template <class T, T t>
struct DStruct
{ int a; };
template <char t>
struct TestEle2<char, t>
{
using typeF = decltype(5);
using typeG = decltype(&DStruct<char, t>::a);
static constexpr typeF f = 5;
static constexpr typeG g = &DStruct<char, t>::a;
};
// This compiles
template <char c>
constexpr typename TestEle2<char, c>::typeF TestEle2<char, c>::f;
// This also compile
template <char c>
constexpr typename TestEle2<char, c>::typeG TestEle2<char, c>::g;
int main()
{
}