【发布时间】:2017-04-07 11:21:08
【问题描述】:
我不明白编译器在这里做什么:
#include <iostream>
using namespace std;
// non-default-constructable struct
struct X
{
X(int v) : x(v) {}
const int x;
};
template< typename T>
struct A
{
static const X a;
};
// trigger a compiler error if we try to instantiate the default template
template< typename T >
const X A<T>::a;
template<>
struct A<int>
{
static const X a;
};
template<>
struct A<float>
{
static const X a;
};
// is this not infinitely circular?
const X A<int>::a = X(A<float>::a.x + 1);
const X A<float>::a = X(A<int>::a.x + 1);
int main() {
// error as expected, A<bool>::a cannot be default-constructed
// cout << A<bool>::a.x << endl;
// this compiles and prints "1 2"
cout << A<int>::a.x << " " << A<float>::a.x << endl;
return 0;
}
我原以为a 的两个专门定义会生成编译器错误,因为它们都是使用另一个的值初始化的,甚至没有可以依赖的默认构造函数。但显然,这在 ideone 中编译并打印 1 2。那么编译器是如何得出X 的两个实例应该用这些值初始化的结论的呢?
【问题讨论】:
-
不,不是,这是未定义的行为。 A
::a 在 A :a 之前没有被赋值,这意味着你只是在读取随机内存
标签: c++ templates instantiation circular-reference