首页 > 解决方案 > 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;
}   

标签: c++templatesc++17metaprogramming

解决方案


You can do it like this:

template<class OtherPrefixType>
Meter operator+(const Meter<OtherPrefixType>& meter) { ... }

推荐阅读