Oneofkind
Oneofkind

Reputation: 31

How to substitute template type T with int

I have a .h file that use template T for a range and other classes use it as int, how to substitute template type T with int or pass in/convert result to Range? How to return the empty() method if T is int type?

 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
};

Upvotes: 0

Views: 64

Answers (1)

John Zwinck
John Zwinck

Reputation: 249163

You can use template specialization. Keep the code you have now and add this below it:

 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; }
};

Upvotes: 1

Related Questions