Does C++ allow templates to take the address of a variable with static storage as a parameter? Since a memory address is integral and those with static storage are known at compile time it seems possible.
I found this question showing that this works for int*.
Is it legal C++ to pass the address of a static const int with no definition to a template?
So far, I haven't convinced my compiler accept pointers to other types like char*.
Can templates be specialized on static addresses in general? If not, why?
Edit: I should have been more explicit. Here is some code that compiles for me using g++ 4.9.
#include <iostream>
template<int* int_addr>
struct temp_on_int{
temp_on_int() {}
void print() {
std::cout << *int_addr << std::endl;
}
};
template<char* str_addr>
struct temp_on_string{
temp_on_string() {}
void print() {
std::cout << str_addr << std::endl;
}
};
static int i = 0;
static char j = 'h';
// static char* k = "hi";
int main() {
temp_on_int<&i> five;
i = 6;
five.print();
temp_on_string<&j> h;
h.print();
// temp_on_string<k> hi;
// hi.print();
}
Commented out is something that won't compile with g++ 4.9. The code as shown won't compile on coliru.
http://coliru.stacked-crooked.com/a/883df3d2b66f9d61
How I compiled:
g++ -std=c++11 -Og -g -march=native -Wall -Wextra -pedantic -ftrapv -fbounds-check -o test16 test16.cpp
The error I get when I try to compile the commented portion:
test16.cpp:33:17: error: the value of 'k' is not usable in a constant expression temp_on_string hi; ^ test16.cpp:22:14: note: 'k' was not declared 'constexpr' static char* k = "hi"; ^ test16.cpp:33:18: error: 'k' is not a valid template argument because 'k' is a variable, not the address of a variable
temp_on_string hi;