gpt4 book ai didi

c++ - 在 C++11 中使用 constexpr 和 auto 的冲突声明

转载 作者:行者123 更新时间:2023-11-30 04:52:31 25 4
gpt4 key购买 nike

我正在试验 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 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

没有定义我有链接问题。我知道这个问题已在 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]

[编辑 2]我正在使用 GCC 4.8.5

最佳答案

考虑以下长评论而不是答案(抱歉)。

我不知道谁是对的(接受所有的 MSVS,接受 f 但拒绝 g 的 g++ 或拒绝 f 的 clang++ > 和 g) 但是,如果我理解正确的话,这是一个更复杂的问题的简化,你不能简单地使用 intint * 而不是 auto

所以我建议在 TestEle2 中插入几个类型

using typeF = decltype(5);
using typeG = decltype(&DStruct<char, t>::a);

并使用它们代替 autodecltype() 用于 fg 类型。

下面是一个完整的编译(g++ 和 c++;我不知道 MSVS(抱歉))示例

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()
{
}

关于c++ - 在 C++11 中使用 constexpr 和 auto 的冲突声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54345310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com