Template problem

Okay so what exactly am I doing wrong here?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//inside class
template<class T>
    const double power(double, T);
//outside class
template<> const double math::power<signed int>(double a, signed int b)
 {
  bool return2 = false;
  double value = a;
 if(b < 0){
 b = absolute(b);
 return2 = true;
 }
 for(unsigned int i = 1; i<b; i++) a *= value;
 if(return2) a = inverse(a);
 return(a); 
}

template<> const double math::power<double>(double a, double b) //error with this line
 {  b *= 10000;
 bool return2 = false; 
 double value = a;
 if(b < 0){ 
b = absolute(b);
 return2 = true; 
} 
for(unsigned int i = 1; i<b; i++) a *= value; 
if(return2) a = inverse(a);
 return(a);
 }


I am getting an error with my second templated function
error: specialization of 'const double math::power(double, T) [with T = double]' after instantiation

Any help or suggestions would be greatly appreciated
-Giblit
ps: I haven't finished the second template function 100% so that it will take in fractions instead of doubles but that doesn't have an effect on my problem because I tried it with an output message and still got the error.
Last edited on
First, you don't actually need templates for this. This is standard function overloading:
1
2
3
4
5
6
7
8
const double math::power(double a, signed int b)
{
    //...
}
const double math::power(double a, double b)
{
    //...
}


However, regarding your errors, I am able to compile this fine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class math
{
public:
    template<class T>
        const double power(double, T);

    template<class T> T absolute(T in) { return in < T(0) ? T(-1)*in : in; }
    template<class T> T inverse(T in) { return T(1) / in; };
};

template<> const double math::power<signed int>(double a, signed int b)
 {
     bool return2 = false;
     double value = a;
     if(b < 0){
         b = absolute(b);
         return2 = true;
     }
     for(unsigned int i = 1; i<b; i++) a *= value;
     if(return2) a = inverse(a);
     return(a);
}

template<> const double math::power<double>(double a, double b) //error with this line
 {  
    b *= 10000;
    bool return2 = false;
    double value = a;
    if(b < 0){
        b = absolute(b);
        return2 = true;
    }
    for(unsigned int i = 1; i<b; i++) a *= value;
    if(return2) a = inverse(a);
    return(a);
}

 int main()
 {
     math a;
     a.power(1.0,1.0);
     a.power(1.0, 1);
 }

still new to c++ I had no idea you could overload functions like that thanks =] I was thinking you had to use templates to overload the functions. And maybe its my compiler though I think its mingw via qt because it did not compile for me I wish i read functions(2) lol http://www.cplusplus.com/doc/tutorial/functions2/
Last edited on
Topic archived. No new replies allowed.