我想确保赋予函数的参数指向(或引用)一个对象,该对象具有静态存储时间 class.
该解决方案需要与 C++11 一起使用,而无需编译器特定的扩展。
我在研究过程中发现的最相似的问题是仅限于C语言的一种 https://stackoverflow.com/q/14829981/5534993。到目前为止,那里提出的解决方案仅适用于编译器特定的扩展。
我想到使用非类型模板参数来限制指向静态存储持续时间的指针,如下所示:
/** @tparam POINTER must point to an integer with static storage duration
* (and linkage [before C++17])
* @return value pointed to by template argument */
template<int * POINTER>
int letPassStaticStorageDurationOnly()
{
return *POINTER;
}
int staticStorageInt = 42; // variable with static storage duration
int* pointerToStaticStorageInt = &staticStorageInt; // pointer to variable
int main()
{
int autoStorageInt = -42;
static int functionStaticInt = -21;
// error: because 'autoStorageInt' has no linkage
return letPassStaticStorageDurationOnly<&autoStorageInt>(); // shall fail
// error: because is a variable, not the address of a variable
return letPassStaticStorageDurationOnly<pointerToStaticStorageInt>();
// error [<C++17]: because 'functionStaticInt' has no linkage
return letPassStaticStorageDurationOnly<&functionStaticInt>();
return letPassStaticStorageDurationOnly<&staticStorageInt>(); // works
}
不幸的是,这(至少)有以下警告:
- 对象必须具有链接(C++17 之前的版本 https://stackoverflow.com/questions/26966901/c11-local-static-values-not-working-as-template-arguments/54655167#comment96102988_26966901)。这不包括例如函数局部静态对象。
- 对于每个指针,都会实例化一个函数模板。我怀疑在实际(生产)部署中通过编译器优化可以避免多少代码重复。将定义有关我的案例中允许使用的优化级别的约束。
如何确保赋予函数的参数仅指向(或引用)静态存储期间的对象?最好没有我概述的建议的警告。欢迎根本不同的解决方案!
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)