Euro Pe
Euro Pe

Reputation: 73

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);
}

Upvotes: 0

Views: 407

Answers (4)

Component 10
Component 10

Reputation: 10507

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. I.e.

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.

Upvotes: 3

Deb S
Deb S

Reputation: 544

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;
}

Upvotes: 2

PapaDiHatti
PapaDiHatti

Reputation: 1921

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*

Upvotes: 1

knst
knst

Reputation: 533

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.

Upvotes: 1

Related Questions