【发布时间】:2023-04-10 03:27:01
【问题描述】:
考虑这段代码:
int x = 0;
template<int& I>
struct SR {};
template<int* I>
struct SP {};
SR<(x)> sr;
SP<&(x)> sp;
int main(void)
{
}
clang++ 3.8.0 抱怨:
main.cpp:10:5: error: non-type template argument does not refer to any declaration
SP<&(x)> sp;
^~~
main.cpp:6:15: note: template parameter is declared here
template<int* I>
^
g++ 6.1.0 抱怨:
main.cpp:10:8: error: template argument 1 is invalid
SP<&(x)> sp;
^
当然,如果我删除括号,一切正常,如SP<&x> sp;。但是我在 C++14 标准中找不到任何可以在这里有所作为的东西。此外,为什么参考案例可以,但指针案例不好?编译器是否正确拒绝程序?
【问题讨论】:
-
@LightnessRacesinOrbit:这个:&(std::cout)-as-template-argument
-
对不起,是的。我想出了一个新的更直接的问题,即为什么是有序的,因为旧问题中如何解决的答案只是“删除括号”。
-
我猜这与在对象名称周围添加括号会使表达式产生右值而不是左值这一事实有关。
-
@LightnessRacesinOrbit 我不确定那里的答案是否能回答问题。它链接到一个专门关于指向成员的指针的问题,但
std::cout是一个对象。 -
@templatetypedef 如果这么简单,你就做不到
int f(int&); int x; int y = f((x));
标签: c++ templates language-lawyer