c++ - Call static function of specialize template with base class of type T
问题描述
I need to write Stream class with a template Write function to accept any type and write it to stream.
I write a Stream class and a StreamWriter to partially specialize Write function, but compiler can't find static function of StreamWriter with base class of AInt class.
template<typename T>
class AType {
public:
T rawValue;
void Add(T v) { rawValue += v; }
void Sub(T v) { rawValue += v; }
void Mul(T v) { rawValue *= v; }
void Mod(T v) { rawValue %= v; }
};
class AInt : public AType<int> {
public:
using AType<int>::Add;
using AType<int>::Sub;
using AType<int>::Mul;
using AType<int>::Mod;
};
class AFloat : public AType<float> {
public:
using AType<float>::Add;
using AType<float>::Sub;
using AType<float>::Mul;
};
class AStream;
template<typename T>
class AStreamWriter {
public:
static bool Write(AStream *stream, T v);
};
class AStream {
public:
template<typename T>
bool Write(T v) {
return AStreamWriter<T>::Write(this, v);
}
};
template<typename T>
class AStreamWriter<AType<T>> {
public:
static bool Write(AStream *stream, AType<T> v) {
//Do somethings
return true;
}
};
int main() {
AInt x{10};
AStream stream;
stream.Write(x); //Error, Compiler can't find AStreamWriter<AInt>::Write
}
Is there any way to fix this problem?
解决方案
您的专业化与(您称为,而不是)AStreamWriter<AType<T>>
无关。AStreamWriter<AInt>
AStreamWriter<AInt>::Write(AStream*, AInt)
AStreamWriter<AType<int>>::Write(AStream*, AType<int>)
重载或简单的模板函数可能是另一种选择......
template<typename T>
static bool Write(const AType<T>&) { return true; }
推荐阅读
- vuetify.js - Vuetify:五列网格布局
- arrays - 由于 python 中的超时,数组操作 Hackerrank 终止
- wordpress - Avada Wordpress 主题:容器背景不起作用
- c# - ASP.NET CORE 2.1 外部登录
- javascript - 字符串的正则表达式数组
- mysql - 结合查询机智
- mongodb - mongodb聚合匹配日期
- java - 开关在另一个内部时形成颜色
- php - 使用不同的 PHP 版本从服务器 B 上的 PHP mysqli 访问服务器 A 上的 MySql 数据库
- python - 使用 BeautifulSoup 和 Requests 解析 html 页面源时出现内存泄漏