C++ Error C2784 – Working with GUID keys in map data structures

Error C2784 is caused by problems with the compiler for using a key in map data structures. Map data structures are very useful in C++, their C# equivalent being the Dictionary structure. They allow you to store data to a key, which means when you come to need that data you can use the key, rather than iterating through a vector or similar.

Error C2784 – Could not deduce template argument

C++ Error C2784

C++ Error C2784

What is it? Error C2784 highlights that the key you are using in your map structure cannot deduce a template argument from a lack of a ‘<' operator.
Common causes C2784 can be caused by any key data type which does not contain an overloaded ‘<' operator. Keys are sorted by the map structure, however, if there is no '<' operator to perform comparisons with, the keys cannot be sorted and, as such, C++ will not compile until it can.
How to fix it? This error can be fixed by providing an overload for the ‘<' operator yourself. The example below shows how to deal with the GUID data structure, which is a common key in maps due to the unique nature of GUIDs (i.e. no two GUIDs will be the same allowing for unique key access). The example given below can be adapted for any data structure which does not contain the necessary '<' operator.

Example fix

The following code is for using GUIDs as keys, but can be adapted as necessary for any data type which needs to fix this error. Commonly, you would put any overloaded operators in the class in which they relate (i.e. if you created your own co-ordinate class and needed to overload the ‘<' operator you would do so in that class) however, this may not always be possible particularly if you are overloading it for a class you have not made. I myself use a common tools file in which I contain some common methods which may be needed across several classes, which is where I place this fix for GUID key mapping.

inline bool operator< (const GUID &firstGUID, const GUID &secondGUID) {
    return (memcmp(&firstGUID, &secondGUID, sizeof(GUID)) < 0 ? true : false);
}

Leave a Reply

Your email address will not be published. Required fields are marked *