【发布时间】:2014-09-20 06:48:50
【问题描述】:
C++ 是否允许模板将具有静态存储的变量的地址作为参数?由于内存地址是完整的,并且具有静态存储的内存地址在编译时已知,这似乎是可能的。
我发现这个问题表明这适用于 int*。
Is it legal C++ to pass the address of a static const int with no definition to a template?
到目前为止,我还没有说服我的编译器接受指向其他类型的指针,例如 char*。
模板一般可以专门用于静态地址吗?如果不是,为什么?
编辑:我应该更明确一点。这是一些使用 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();
}
注释掉的是不能用 g++ 4.9 编译的东西。所示代码无法在 coliru 上编译。
http://coliru.stacked-crooked.com/a/883df3d2b66f9d61
我是如何编译的:
g++ -std=c++11 -Og -g -march=native -Wall -Wextra -pedantic -ftrapv -fbounds-check -o test16 test16.cpp
我尝试编译注释部分时遇到的错误:
test16.cpp:33:17: 错误:'k' 的值不能用于常量 表达式 temp_on_string 嗨; ^ test16.cpp:22:14: 注意:'k' 没有被声明为 'constexpr' static char* k = "hi"; ^ test16.cpp:33:18: 错误:“k”不是有效的模板参数,因为“k”是一个变量,而不是变量的地址
temp_on_string hi;
【问题讨论】:
-
你是说你的编译器接受了那个代码,但是如果你把
int改成char,然后什么都不改,你的编译器会拒绝它吗? -
问题不清楚 - 已编辑。