Home > Back-end >  How to provide a default parameter argument when the type of that parameter is a template type?
How to provide a default parameter argument when the type of that parameter is a template type?

Time:10-06

template <class V, class K>    
class Pair {
public:
    Pair(const K& key, const V& value = initial) {  // what should "initial" be here?
        // ...
    }
}

For example if I use the class like this:

int main() {
    Pair<int, std::string> p1(21);  // p1 should be {21, ""} as the default value of a string is "".
    Pair<int, double> p2(20);  // p2 should be {20, 0.0} assuming the default value of a double is 0.0
}

How can I achieve this?

CodePudding user response:

Try V() like:

template <class K, class V>    
class Pair {
 public:
  Pair(const K& key, const V& value = V()) { }
};

Or:

template <class K, class V>    
class Pair {
 public:
  Pair(const K& key, const V& value = {}) { }
};

Note that a default constructor is required (which is callable without arguments).

  • Related