0

Is there a way to use same template function for performing operation on int and std::string, eg:

template<typename T>
T add(typename a, typename b)
{
   return (a+b);       // incase for int
   return a.append(b); // incase for std::string
}

Any help is appreciated.

3
  • 3
    Why do you think a+b won't work for strings if a and b both are strings ? Commented Feb 14, 2017 at 4:01
  • Did you try it? Did it not work? Commented Feb 14, 2017 at 4:09
  • What you are trying to do is a different operation for int and string. For int you are trying to add two integers to produce a 3rd integer, but for the string you are trying to append one string to the other. i.e. not producing a third string, but mutating one of the input arguments. As others have stated, if you are happy to produce a third string you can just do a + b for both. Commented Feb 14, 2017 at 4:10

1 Answer 1

1

std::string supports the operator+.

concatenates two strings or a string and a char

template<typemane T>
T add(typename a, typename b)
{
   return a + b;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.