gpt4 book ai didi

c++ - 带有模板类的 constexpr 和静态成员声明

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:52:21 24 4
gpt4 key购买 nike

请看代码:

#include <iostream>
#include <typeinfo>

template<int N>
struct C
{
static constexpr int n = N;
using this_type_1 = C<n>;
using this_type_2 = C<N>;
static this_type_1* p_1;
static this_type_2* p_2;
};

template<int N>
//C<N>* C<N>::p_1; // <--- error pattern
typename C<N>::this_type_1* C<N>::p_1; // <--- ok pattern

template<int N>
C<N>* C<N>::p_2; // ok

int main(){
std::cerr
<< typeid(C<0>).name() << "\n"
<< typeid(C<0>::this_type_1).name() << "\n"
<< typeid(C<0>::this_type_2).name() << "\n"
;
}

可以用g++-4.7.1和clang++-3.1编译。但是它不能用注释掉的错误模式编译。

g++ 错误信息是:

test.cpp:15:13: error: conflicting declaration ‘C<N>* C<N>::p_1’
test.cpp:10:23: error: ‘C<N>::p_1’ has a previous declaration as ‘C<N>::this_type_1* C<N>::p_1’
test.cpp:15:13: error: declaration of ‘C<N>::this_type_1* C<N>::p_1’ outside of class is not definition [-fpermissive]

clang++ 错误信息是:

test.cpp:15:13: error: redefinition of 'p_1' with a different type
C<N>* C<N>::p_1; // error
^
test.cpp:10:23: note: previous definition is here
static this_type_1* p_1;
^
1 error generated.

幸运的是,我找到了一个工作模式。但是不知道为什么 错误模式无法编译。请根据C++语言规范告诉我原因。

最佳答案

C<N>::p_1 的两个可能定义并不像它们看起来那样等价,因为 C<N>::n可以在给定 N 的第一次实例化之前的任何时间明确特化.

template<int N>
struct C
{
static constexpr int n = N;
using this_type_1 = C<n>;
static this_type_1* p_1;
};

template<int N>
C<N>* C<N>::p_1; // ERROR

template<>
constexpr int C<5>::n = 6;

int main()
{
C<6>* p = C<5>::p_1;
}

如果编译器接受了 C<N>::p_1 的定义,它声明的类型可能不正确。

关于c++ - 带有模板类的 constexpr 和静态成员声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419679/

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