views:

254

answers:

2

I have a class like

template <class T>
struct A{
    template <class U>
    A(U u);
};

I would like to write an explicit specialization of this for a declaration like

A<int>::A(float);

In the following test code, if I comment out the specialization, it compiles with g++. Otherwise, it says I have the wrong number of template parameters:

#include <iostream>

template <class T>
struct A{
    template <class U>
    A(T t, U *u){
        *u += U(t);
    }
};

template <>
template <>
A<int>::A<int,float>(int t, float *u){
    *u += float(2*t);
}

int main(){
    float f = 0;
    int i = 1;
    A<int>(i, &f);
    std::cout << f << std::endl;
    return 0;
}
+3  A: 

Try

template <>
template <>
A<int>::A(int t, float *u){
     *u += float(2*t);
}

That seems to work for me.

cpalmer
Oops, I have a typo there; the U should be float, let me fix that.
Victor Liu
Ok, this seems to work, but it relies on specifying the parameters implicitly. Is this the only way to do it?
Victor Liu
This is also what works on VC++2008.
conio
+1  A: 

The definition's function parameter list should match the declaration's.

template <>
template <>
A<int>::A<float>(int t, float *u){
    *u += U(2*t);
}
Potatoswatter
with `U` replaced with float, this compiles with Comeau, but it does not compile with gcc
smerlin
I found http://gcc.gnu.org/bugzilla/show_bug.cgi?id=9050 . The problem is specific to constructors.
Potatoswatter