c++ - 具有静态存储的变量地址模板

标签 c++ templates static

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: 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;

最佳答案

14.3.2
  Template non-type arguments [temp.arg.nontype]
    1
      A template-argument for a non-type, non-template template-parameter shall be one of: [...]
  • a constant expression (5.19) that designates the address of a complete object with static storage duration and external or internal linkage or a function with external or internal linkage
     [...]

因为 k 不是常量表达式,所以不能将它用作模板参数。

如果将 k 的声明替换为

static char k[] = "hi";

clang++ 编译它。 g++ 没有;这是 IMO g++ 中的错误。

如果k声明为

namespace { char k[] = "hi"; }

然后 g++ 也编译它。

关于c++ - 具有静态存储的变量地址模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25946089/

相关文章:

c++ - 如何确定数组中的第一个索引是否为负号

c++ - C++ 中的两阶段构造

c++ - 如何对不同类型的数组正确使用 memcpy

java - 如何将其添加到静态方法中的数组列表中?

c++ - 从动态 dll 访问静态链接库中的静态变量/函数

c# - Winpcap 简单问题——如何向指定的ip/端口发送数据包?

c++ - 列表初始化器和可变参数构造函数

c++ - 限制基本模板实例化

c++ - 模板类的接口(interface)

asp.net - ASP.NET MVC 中静态方法和非静态方法的区别