简体   繁体   中英

C++ specialized function template

I started using templates and I have a problem. I want to use function sum to the type char* and it fails to compile.

Error I got:

cannot initialize return object of type 'char*' with an rvalue of type 'int'

Code:

#include <iostream>

using namespace std;

template<class T>
T sum(const T a, const T b){
    return (a+b);
}

char* sum(char* a, char* b){
    return (*a + *b);
}

Start by asking what is sum(char* a, char* b) meant to do? The parameters are strings, not numbers so probably the operation should concatenate two strings? Write something that will achieve this:

char* sum(char* a, char* b){
    char* sum = new char[ strlen(a) + strlen(b) + 1 ];
    memcpy(sum, a, strlen(a));
    memcpy(sum + strlen(a), b, strlen(b));
    sum[strlen(a) + strlen(b)] = '\0';
    return sum;
}

Now you can, if you think it adds value, specialise the sum template function to make it do what you want it to. Ie

template<>
char* sum<char*>(char* a, char* b){
...

So now you can do this:

int c = sum(5, 7);
cout << c << endl;

char face[5] = {'F', 'a', 'c', 'e', '\0'};
char book[5] = {'b', 'o', 'o', 'k', '\0'};
char* raw = sum(face, book);
cout << raw << endl;
delete [] raw; // Remember you need to delete the heap that sum() grabbed.

Output:

12
Facebook

This example is, of course quite crude and not something you'd want to do in important code. I'm assuming that this is just an exercise as specialising in this way does not add any specific value and, of course, this is already achieved in the standard library in different ways.

You cannot return *a+*b , not even return *a ; you can retun a (see yoy return type)

If you want to add two string then write function like this -

char* sum(char* a, char* b){
    char * ret = (char *) malloc(1 + strlen(a)+ strlen(b) );
    strcpy(ret, a);
    strcat(ret, b);
    return ret;
}

This problem doesn't related to template, problem in code:

char* sum(char* a, char* b) {
    return (*a + *b);
}

Because type of (*a) is char (not char*), type of (*a + *b) is int (auto cast to int in arithmetic) and int couldn't convert to "char *" that is type of return value.

Assuming sum means concatenation for char* data types then your code should be like below :

char* sum(char* a, char* b){
    char *ret = a;
    strcat(ret,b);
    return ret;
}

As + operator is not overloaded for char* and if you have option then string should be used instead of char*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM