【问题标题】:Constraing template parameter by another template with any specialization type由具有任何特化类型的另一个模板约束模板参数
【发布时间】:2021-05-29 17:42:36
【问题描述】:

我开始使用模板并想出了编写简单的仅包含标题的单元库的想法。我遇到了定义参数类型约束的问题。类型本身也是一个模板。我的要求是将类型限制为键入任何模板专业化类型“前缀”的“仪表”。我希望下面的代码能说明问题,非常感谢任何建议。

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++ templates c++17 metaprogramming


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      我创建了临时对象以在Prefix 中使用getVal() 函数。 在这里,我的解决方案,

      #include <iostream>
      
      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 Meter<AnyMeterType>& meter){
              return PrefixType{}.getVal()*val + AnyMeterType{}.getVal()*meter.getVal();
          }  
      
          friend std::ostream& operator<<(std::ostream &os, const Meter &m)
          {
              os << m.val;
              return os;
          }
      
          double getVal() const
          {
              return val;
          }
      
        private:
          double val;
      };
      
      int main()
      {
          Meter<Micro> d1{1000};
          Meter<Milli> d2{1};
          Meter<Milli> d3 = d2 + d1;
      
          // d3.val == 2
          std::cout << d3;
          return 0;
      }   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-16
        • 1970-01-01
        • 1970-01-01
        • 2011-07-26
        相关资源
        最近更新 更多