c++ - 继承和模板运算符重载

标签 c++ templates inheritance operator-overloading

继承和模板运算符重载

我不明白为什么 A<int> 中的运算符掩盖了 base 中的运算符. 毕竟它有不同的签名。

#include <iostream>

struct base {
  template <typename U>
  void operator()(U&& x) { std::cout << "base" << std::endl; }
};

template <typename T>
struct A: public base { };

template <>
struct A<int>: public base {
  void operator()() { std::cout << "A<int>" << std::endl; } // line 1
};

int main()
{
  A<double>()(1);
  A<int>()(1); // line 2
  A<int>()();  // line 3
}

如果存在第 1 行,则第 2 行不会编译。

如果删除第 1 行(显然),第 3 行将无法编译。

如果我将运算符模板从 base 复制到 A,一切正常。

我期望输出是:

base
base
A<int>

最佳答案

运算符在派生类中的声明隐藏了基类中的名称。
解决这个问题,这是一个 using declaration 的问题:

template <>
struct A<int>: public base {
    using base::operator();
    void operator()() { std::cout << "A<int>" << std::endl; }
};

而且它们都可以编译。

关于c++ - 继承和模板运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37846188/

相关文章:

c++ - 在构造函数中调用虚函数

c++ - 无法在另一个类中实例化模板化类

python - 是否可以在子类中重写属性的 getter?

java - 获取列表中具有特定泛型类型的元素

c++ - 为什么容器需要const

C++:将 int 转换为 unsigned char

c++ - 如何标记 C 字符串的结尾?

C++编译器模板错误信息-解码错误信息的工具

python - Python 中是否有用于纯文本文件的 native 模板系统?

.NET 抽象类