3
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?

0

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.