C++ explicit template specialization of templated constructor of templated class

て烟熏妆下的殇ゞ 提交于 2019-12-23 09:46:34

问题


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

回答1:


Try

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

That seems to work for me.




回答2:


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


来源:https://stackoverflow.com/questions/2563165/c-explicit-template-specialization-of-templated-constructor-of-templated-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!