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

后端 未结 5 1989
予麋鹿
予麋鹿 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:49

    Even though the question has been answered by others with answers on how to specialize std::less (by wrap them in a namespace block) and the right way to do it ( to overload operator <).

    However, C++ now allows (in C++11) to speciliaze the way you did in your first example.

    An explicit specialization shall be declared in a namespace enclosing the specialized template. An explicit specialization whose declarator-id is not qualified shall be declared in the nearest enclosing namespace of the template, or, if the namespace is inline (7.3.1), any namespace from its enclosing namespace set. Such a declaration may also be a definition. If the declaration is not a definition, the specialization may be defined later (7.3.1.2).

    I tried the following code with g++ (8.3.0) on my Ubuntu machine.

    #include 
    
    #include 
    #include 
    #include 
    
    
    class myType {
    
    public:
        myType(int in): i_(in) { }
    
        int i_;
    };
    
    template <>
    struct std::less  {
        bool operator()(const myType& a, const myType& b) const
        {
            return a.i_ < b.i_;
        }
    };
    
    
    int main(int argc, char *argv[])
    {
        std::map vector = { { 1, "1"}, { 2, "2"}, { 3, "3"}, { 0, "0" } };
    
        for (auto& i: vector)
            std::cout << i.first.i_ << std::endl;
        return 0;
    }
    

    The above code was compiled with

    g++ --std=c++11 compare.cpp -Wall 
    

提交回复
热议问题