【发布时间】:2016-01-31 07:12:51
【问题描述】:
template <int* ip> struct test {};
struct q {
static int a;
int b;
constexpr q(int b_) : b(b_) {}
};
int i;
constexpr q q0(2);
int main()
{
constexpr test<&i> t1; // Works fine
constexpr test<&q::a> t2; // Works
constexpr test<&q0.b> t3; // Does not work; address of non-static member?
return 0;
}
尽管模板参数&q0.b 在编译时已知,但上述代码中的 t3 声明失败。一些谷歌搜索显示标准不允许这样做(第 14.3.2 节):
[注意:数组元素的地址和非静态类成员的名称或地址不是可接受的模板参数。
X x4; // 错误:非静态成员的地址
那么,尽管全局变量的非静态成员的地址是唯一的并且在编译时是已知的,但为什么标准明确不允许这样做呢?
【问题讨论】:
-
我在 gcc 5.1.1 和 clang 3.5.0 上用 -std=c++11 试过这个
-
No
(new q)->b在编译时未知 -
它的类型不是
int*,是int q::*,不是吗? -
@ShafikYaghmour 我删除了它,因为问题更多的是“为什么存在这个限制”而不是“为什么这段代码不能编译?”无论哪种方式,这两种措辞都是不允许的。
-
模板参数必须被破坏,并且破坏(任意复杂)对子对象的引用是一大堆蠕虫。
标签: c++ templates language-lawyer