如何用int替换模板类型T.

时间:2017-04-22 05:28:45

标签: c++11

我有一个.h文件,它使用模板T作为范围,其他类使用它作为int,如何用int替换模板类型T或传入/转换结果到Range?如果T是int类型,如何返回empty()方法?

 template<typename T>
 struct Range {
   T lowerBound;
   T upperBound;
   static Range<T> createFromJson(const Json::Value & val) {
        Range<T> result;
        if (val.isMember("lowerBound") && val.isMember("upperBound")) {
            result.lowerBound = val["lowerBound"];//.asInt();//should use T
            result.upperBound = val["upperBound"];//.asInt();//should use T
        } else {
            throw ML::Exception("error parsing lower/upper %s in %s",  "There was given: %s",
                        val.asCString());
        }
        return result;
   }

    bool empty() const { return lowerBound.empty() && upperBound.empty(); }//shouldn't be empty for int
};

1 个答案:

答案 0 :(得分:1)

您可以使用模板专业化。保留现有代码并在其下方添加:

 template<>
 struct Range<int> {
   int lowerBound = 0;
   int upperBound = 0;
   static Range<int> createFromJson(const Json::Value & val) {
        Range<int> result;
        if (val.isMember("lowerBound") && val.isMember("upperBound")) {
            result.lowerBound = val["lowerBound"].asInt();
            result.upperBound = val["upperBound"].asInt();
        } else {
            throw ML::Exception("error parsing lower/upper %s in %s",  "There was given: %s",
                        val.asCString());
        }
        return result;
   }

   bool empty() const { return lowerBound == upperBound; }
};