I would like to make sure that an argument given to a function points to (or references to) an object which has static storage duration class.
The solution needs to work with C++11 without compiler specific extensions.
The most similar question I found during my research is one which is limited to C language. The solutions proposed there, until now, work only with compiler specific extensions.
I thought of using non-type template parameters to restrict pointers to static storage duration like this:
/** @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
}
Unfortunately this has (at least) the following caveats:
- Objects must have linkage (prior to C++17). This excludes for example function local static objects.
- For each pointer a function template is instantiated. I am skeptical how much code duplication can be avoided by compiler optimization in the actual (productive) deployment. Constraints regarding the optimization level allowed to use in my case are to be defined.
How can one ensure arguments, given to functions, point to (or reference to) objects in static storage duration only? Preferably without the caveats of the proposal I outlined. Fundamentally different solutions are welcome!