What is the correct way to declare template specialization for another type of template?

A typical template function specialization definition looks something like this:

class Foo {
    [...]
};

namespace std {
    template<>
    void swap(Foo& left, Foo& right) {
        [...]
    }
} // namespace std

But how do you correctly define specialization when the type it specializes in is itself a template? Here is what I have:

template <size_t Bits>
class fixed {
    [...]
};

namespace std {
    template<size_t Bits>
    void swap(fixed<Bits>& left, fixed<Bits>& right) {
        [...]
    }
} // namespace std

Is this right to declare swap? It should be a specialization of the template function std::swap, but I cannot say if the compiler sees it as such or thinks it overloads it or something like that.

+3
source share
4 answers

Your decision is not a specialization of the template, but an overload of the function in the std namespace, which is the "undefined behavior" according to the C ++ standard.

- .

Effective ++, usenet comp.lang.++.

std, , , :) namespace std "fixed" std::fixed, .

+4

, fixed<Bits> , .

, std::swap(a, b) . , std::swap. , .

+3

"" . , , , . .

, - std (. 17.4.3.1/1). , , std , std::swap. swap , , std, , yor fixed. ( "Koenig lookup" ) , swap fixed ( std::swap, swap).

+2

A template parameter cannot be declared with a value that is not defined before runtime. To use numbers for a template parameter, it must be "const", so it can be solved at compile time:

template <const size_t Bits> 
class fixed { 
    [...] 
}; 

namespace std { 
    template<const size_t Bits> 
    void swap(fixed<Bits>& left, fixed<Bits>& right) { 
        [...] 
    } 
} // namespace std 
-4
source

Source: https://habr.com/ru/post/1743103/


All Articles