Specialization of 'template struct std::less' in different namespace

后端 未结 5 1986
予麋鹿
予麋鹿 2020-12-03 13:42

I am specializing the \'less\' (predicate) for a data type.

The code looks like this:

template<>
struct std::less
{
   bool          


        
5条回答
  •  不思量自难忘°
    2020-12-03 13:43

    If you need to specialize a standard algorithm, you can do so in the std namespace. It is the only thing that you are allowed to do inside that namespace according to the standard.

    [lib.reserved.names]/1

    It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces within namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library template results in undefined behavior unless the declaration depends on a user-defined name of external linkage and unless the specialization meets the standard library requirements for the original template

    Now, the question is whether you actually want to specialize std::less. Note that std::less will call the comparison operator defined for your type, so you can provide that operation instead of specializing the template.

    The problem with specializing std::less for your particular type is that it will cause confusion if you provide a different operation than the one performed by operator< for your type. If they perform the same operation, just leave the default std::less definition without specialization.

    If you do not want to provide the comparison operator, but still want to use the type in associative containers or with algorithms that require a comparator, you can provide an external comparison functor by other name that will not confuse other readers (and yourself somewhere in the future).

提交回复
热议问题