gpt4 book ai didi

c++ - 模板、继承、静态成员增量

转载 作者:行者123 更新时间:2023-11-28 04:14:48 24 4
gpt4 key购买 nike

以下代码在我看来应该输出sum sizeof(int) + sizeof(float) + sizeof(std::string),但存储值始终为零。为什么?

struct Base {
static int IncrementID(int x) {
static int id = 0;
storage += x;
return id++;
}
static int storage;
};
int Base::storage = 0;

template<typename T>
struct Object : public Base {
static const int id;
};
template<typename T>
const int Object<T>::id(Base::IncrementID(sizeof(T)));

int main() {
Object<int> a;
Object<float> b;
Object<std::string> c;

std::cout << Base::storage;
}

最佳答案

您不要以任何可能导致其隐式实例化的方式使用这些静态 id 数据成员。这意味着它们不必被实例化(也不必进行初始化)。引用 C++ 标准:

[temp.inst]

3 Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

做一些像添加用户定义的构造函数一样简单的事情

Object() {
int i = id;
(void)i;
}

Can be enough ODR-使用它们,并像您一样通过创建对象来强制实例化它们。

关于c++ - 模板、继承、静态成员增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914001/

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