模板化类的模板化构造函数的 C++ 显式模板特化 [英] C++ explicit template specialization of templated constructor of templated class
本文介绍了模板化类的模板化构造函数的 C++ 显式模板特化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的课程
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);
在下面的测试代码中,如果我将特化注释掉,它会用 g++ 编译.否则,它说我的模板参数数量错误:
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;
}
推荐答案
尝试
template <>
template <>
A<int>::A(int t, float *u){
*u += float(2*t);
}
这似乎对我有用.
这篇关于模板化类的模板化构造函数的 C++ 显式模板特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文