Pra*_*tic 2 c++ static templates
C++ 是否允许模板将具有静态存储的变量的地址作为参数?由于内存地址是完整的,并且那些具有静态存储的在编译时是已知的,这似乎是可能的。
我发现这个问题表明这适用于 int*。
将没有定义的静态 const int 的地址传递给模板是否合法?
到目前为止,我还没有说服我的编译器接受指向其他类型(如 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();
}
Run Code Online (Sandbox Code Playgroud)
注释掉的是不能用 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 hi 中不可用;^ test16.cpp:22:14: 注意:'k' 未声明为 'constexpr' static char* k = "hi"; ^ test16.cpp:33:18: 错误:'k' 不是有效的模板参数,因为 'k' 是一个变量,而不是变量
temp_on_string hi的地址;
14.3.2
模板非类型参数 [temp.arg.nontype]
1
非类型、非模板模板参数的模板参数应为以下之一:[...][...]
- 一个常量表达式 (5.19),它指定具有静态存储持续时间和外部或内部链接的完整对象或具有外部或内部链接的函数的地址
自从 k
不是常量表达式,因此不能将其用作模板参数。
如果更换的声明k
与
static char k[] = "hi";
Run Code Online (Sandbox Code Playgroud)
clang++
编译它。g++
才不是; 这是 IMO 中的一个错误g++
。
如果k
声明为
namespace { char k[] = "hi"; }
Run Code Online (Sandbox Code Playgroud)
然后也g++
编译它。