c++ - 将对基类的引用作为模板参数传递

标签 c++ templates

我有以下代码,我尝试为类的每个实例(可能已派生)专门化一个函数模板:

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'

[live demo]

在给定静态 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/

相关文章:

c++ - 打印出文件的最后 10 行

c++ - 如何在 C++ 中将精确的浮点值保存和恢复到人类可读文件

node.js - Nunjucks: 'if' 与多个 'and' 或 'or' 条件

java - 如何在独立应用程序中使用 Java Facelets 作为通用模板引擎?

无论模板类型如何,结构的 C++ 函数

javascript - 快速路由——路由到/secrets时出现404错误,我错过了什么

c++ - 允许成员函数使用左值和右值引用限定符的目的是什么?

c++ - 指向特定类型的 STL 容器样式和迭代器 (C++)

c++ - 如何将 Qt Creator 配置为用户 MSVC2015?

c++ - 嵌套名称说明符