using namespace std; template vo...">

Error creating template

I have a "compare" template function as shown below.

#include<iostream>
using namespace std;

template<typename T>
void compare(const T&a, const T& b)
{
    cout<<"Inside compare"<<endl;
}

main()
{
compare("aa","bb");
compare("aa","bbbb");
}

When I create a comparison with string literals of the same length, the compiler does not complain. When I do this with literals of different lengths, he says: "Error: there is no corresponding function to call for comparison (const char [3], const char [5])"

I am confused because the comparison function should be created with a character pointer, not an array of characters. Shouldn't string literals always break into a pointer?

+5
source share
3 answers

โ€‹โ€‹ , ( , ). as- , , , .

void compare(char const* a, char const* b) {
    // do something, possibly use strlen()
}

template<int N1, int N2>
void compare(char const (&a)[N1], char const (&b)[N2]) {
    // ...
}

, , :

compare<char const*>("aa", "bbbb");

, , ? , . , f(a), a.size() < b.size() f(b) ( f). (T1 T2 , , , .)

template<typename T1, typename T2>
void compare(T1 const& a, T2 const& b) {
    // ...
}
+4

, :

void compare(const T* a, const T* b)

, . sizeof(T) , , . T, const char* .

+6

, . , const char *. , , . . , T const char [3], . .

compare(static_cast<const char *>("aa"),static_cast<const char *>("bbbb"));

.

+3
source

All Articles