-1

I am having difficulty understanding the syntax of this code fragment

What is the purpose of "const K& k = K(), const V& v = V()"?

template<typename K, typename V>
class Entry{

    public:
        typedef K Key;
        typedef V Value;
    public:
        Entry(const K& k = K(), const V& v = V()) : _key(k), _value(v) {}

    ....
        ....
            ....
    private:
        K _key;
        V _value;
};

Thank you

sbryan1
  • 21
  • 4

1 Answers1

1

K and V are template parameters, they can be any data type the user of Entry wants.

k and v are input parameters of the Entry constructor. They are being passed in by const reference, and they have default values specified, where K() default-constructs a temp object of type K, and V() default-constructs a temp object of type V. If the user does not provide explicit input values when creating an Entry object instance, the defaults are used instead.

For example:

Entry<int, int> e1(1, 2);
// K = int, k = 1
// V = int, v = 2

Entry<int, int> e2(1);
// aka Entry<int, int> e2(1, int())
// K = int, k = 1
// V = int, v = 0

Entry<int, int> e3;
// aka Entry<int, int> e3(int(), int())
// K = int, k = 0
// V = int, v = 0

Entry<std::string, std::string> e4("key", "value");
// K = std::string, k = "key"
// V = std::string, v = "value"

Entry<std::string, std::string> e5("key");
// aka Entry<std::string, std::string> e4("key", std::string())
// K = std::string, k = "key"
// V = std::string, v = ""

Entry<std::string, std::string> e6;
// aka Entry<std::string, std::string> e4(std::string(), std::string())
// K = std::string, k = ""
// V = std::string, v = ""
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770