Explicit template specialization

This is my function template.

template<class T> const T& min(const T& a, const T& b) {
return (a < b) ? a : b;
}

The sole purpose of the function is to return min from two arguments. Arguments are read only.

Here is the explicit specialization for char * arguments

//Code 1:
    template<>
    const char*& min<const char*>(const char* &a,
    const char* &b) {
    return (strcmp(a, b) < 0) ? a : b;
    }

Although only an argument is read, this code gives an error. Although the code below works fine

//Code 2:    
template<>
    const char* const& min<const char*>(const char* const& a,
    const char* const& b) {
    return (strcmp(a, b) < 0) ? a : b;
    }

Why do I need to provide const & after char * if & or const is enough to read only the arguments. What is the meaning of const & in code 2 .. ??

Edition:

I get this error code when compiling with code 1 ..

error: template-id 'min<const char*>' for 'const char* const& min(const char*&, const char*&)' does not match any template declaration|

while the compilation error code with code 2 is missing.

+4
source share
2

template<class T> const T& min(const T& a, const T& b) {...}

const T& T const &, T. , . const char* ( char const *, char), : char const * const &, char.

, const , , const , , .

( , ):

min:

const char* min(const char* a, const char* b) {
    return (strcmp(a, b) < 0) ? a : b;
}
+3

char*.

1-

const char* const& min<const char*>(const char* &a,
const char* &b)

, .

const char* const& min<const char*>(const char* const& a,
const char* const& b)

.
, .

+1

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


All Articles