继承和模板运算符重载
我不明白为什么 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/