0

I have made this code to add numbers by adding first argument if you ask why i make it like

that because i will use it to solve a problem in my assignment the code works fine if the numbers are from the same data type for example int and int but if it is from different data types like double and int it no longer works as if static key word on m is not exist

#include<iostream>
using namespace std;
template <class first, class seconde>
void total (first a, seconde b){
    static first m =0 ;
    static seconde f=0;
    ++f;
    if(b==m){
        m+=a;
        cout<<m<<endl;
    }
        m+=a;
}

void main(){
    total(2,2);
    total(1,2);
    system("pause");
}

i need to know it dose not work with different data types when using int and double while iam using template

7
  • it will work fine if i put 2.1 and 2.5 not 2.1 and 2 Commented Dec 4, 2013 at 15:29
  • what is the error message? Commented Dec 4, 2013 at 15:30
  • 1
    Each template specialisation will have its own static variables. If you want to share them between all specialisations, then you'll have to either make them global, or come up with a less nasty way to maintain state between function calls. Commented Dec 4, 2013 at 15:31
  • spiritwolfform no error message when different data types just null Commented Dec 4, 2013 at 15:32
  • 1
    Please define "does not work." Commented Dec 4, 2013 at 15:36

1 Answer 1

3

With templates, different template parameters creates a completely different and unrelated function.

Just remember that for every different combination of first and seconde you will have different static variables. Each different combo of template parameters generates a new function, so calling

total(1, 2) // calls total<int, int>

and

total(1, 1.3) // calls total<int, double> , a totally different function

will not access the same static variables.

Sign up to request clarification or add additional context in comments.

9 Comments

they access the same one if they are of same data types you can try it
@user2918388 I know, but you said your problem was when you used it with different data types. I just told you why.
okay thank you but why that behavior when different combination
@user2918388 because they're two different functions. Each different combo of types makes a new function unrelated to the others. They don't share static variables. total<int, int> and total<int, double> are so unrelated that they might as well be named foo and bar.
@uk4321 +1 (both answer and comment). I'd just add that even total<double, int> is absolutely unrelated to total<int, double> (and all the others).
|

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.