我有以下代码,我尝试为类的每个实例(可能已派生)专门化一个函数模板:
class Base {
};
class Derived:public Base {
};
template<Base& b>
void myfunction() {
//use b somehow
}
Derived myobject;
int main() {
myfunction<myobject>(); //this does not work
}
代码导致错误消息:
candidate template ignored: invalid explicitly-specified argument for template parameter 'b'
在给定静态 Derived
对象 myobject
的情况下,如何传递对类型 Base
的静态实例的引用?
最佳答案
虽然根据 [temp.param]/4 将模板非类型参数 声明为引用是 没问题的:
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- ...
- lvalue reference to object or lvalue reference to function,
- ...
参数必须遵循[temp.arg.nontype]/2中的限制:
A template-argument for a non-type template-parameter shall be a converted constant expression of the type of the template-parameter. For a non-type template-parameter of reference or pointer type, the value of the constant expression shall not refer to (or for a pointer type, shall not be the address of):
- a subobject,
- ...
这明确禁止您尝试做的事情。因为 b
最终将引用一个子对象。
唯一可以编译的解决方案是添加另一个重载:
template<Derived & d>
void myfunction()
{
//use d somehow
}
因此您需要以某种方式提取通用代码。
或者,如果您有可用的 C++17:
template<auto& b, std::enable_if_t<
std::is_base_of_v<Base, std::decay_t<decltype(b)>>
, void*> = nullptr>
void myfunction()
{
//use b somehow
}
不过,我建议您重新考虑您的一般方法。
关于c++ - 将对基类的引用作为模板参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46153145/