c++ - Constraing template parameter by another template with any specialization type
问题描述
I started playing around with templates and came up with idea of writting simple header-only unit library. I came accross a problem with defining a constaint on parameter type. The type itself is also a template. My requirement is to constraing the type to type 'Meter' of any template specialization type 'Prefix'. I hope the code below will speak for itself, thank's a lot in advance for any suggestions.
template<int PrefixVal>
struct Prefix {
constexpr int getVal() { return PrefixVal;}
};
struct Micro : public Prefix<-1000000>{};
struct Milli : public Prefix<-1000>{};
template<class PrefixType>
class Meter {
public:
Meter(double v) : val(v) {}
template<class AnyMeterType>
Meter operator+(const AnyMeterType& meter){
// How to constrain AnyMeterType to be
// type Meter<AnyPrefix>?
}
private:
double val;
};
int main()
{
Meter<Micro> d1{1000};
Meter<Milli> d2{1};
Meter<Milli> d3 = d2 + d1;
// d3.val == 2
return 0;
}
解决方案
You can do it like this:
template<class OtherPrefixType>
Meter operator+(const Meter<OtherPrefixType>& meter) { ... }
推荐阅读
- serialization - Django rest 框架:有没有办法在使用序列化程序验证数据之前清理数据?
- logstash - Logstash 配置错误,我认为这是一个愚蠢的问题
- c++ - 有没有办法用忍者生成器在cmake中禁用“deps = gcc”的生成?
- jquery - 具有类对象和布尔数据类型的 Jquery ajax 调用
- javascript - 将猫鼬中的字符串日期与 Date.now() 或 new Date() 进行比较
- python - 使用同一类的方法为类导入模块
- mysql - 如何制作具有更好性能的 COUNT?
- javascript - 将 HTML 文本放在特定位置但在同一行
- c# - 使用 C# 驱动程序使用 Elemmatch 查询 MongoDB
- r - 推断/表达拟合平滑样条的多项式方程?