【发布时间】:2015-09-25 18:51:55
【问题描述】:
考虑代码:
class Base{};
class Derived: public Base{};
template<Base& b> // references (and pointers) can be used as non-types
void f(){}
int main()
{
Derived d;
// f(d); // Error, template type must match exactly
f<(Base&)d>(); // Error here, why?!
}
我理解注释调用失败的原因:模板类型必须完全匹配。但是,我尝试在第二次调用中进行强制转换,并收到此错误(gcc5.2):
错误:“d”不是“Base&”类型的有效模板参数,因为它不是具有外部链接的对象
如果我将Derived d; 设为全局,则会出现同样的错误。 clang 更有帮助,说
...注意:候选模板被忽略:显式指定无效 模板参数“b”的参数
我的问题是:上面的代码是否合法?如果不是,有什么原因吗?
【问题讨论】: