Gab*_*iel 4 c++ templates template-specialization
我想写这个:
template<typename T1, typename T2>
class OK
{
T1 t1;
T2 t2;
public:
template<typename TX> const TX & GetRef() const;
};
template<typename T1,typename T2>
template<>
const T1 & OK<T1,T2>::GetRef<T1>() const { return t1; }
template<typename T1,typename T2>
template<>
const T2 & OK<T1,T2>::GetRef<T2>() const { return t2; }
Run Code Online (Sandbox Code Playgroud)
哪个VS10无法编译.
为了检查我对模板专业化的理解,我尝试并编译了这一点:
typedef int T1;
typedef char T2;
class OK
{
T1 t1;
T2 t2;
public:
template<typename TX> const TX & GetRef() const;
};
template<>
const T1 & OK::GetRef<T1>() const { return t1; }
template<>
const T2 & OK::GetRef<T2>() const { return t2; }
Run Code Online (Sandbox Code Playgroud)
我错过了什么?我甚至想做什么?
编辑:我想要所有字段的getter,所有调用GetRef(),所以用户可以编写如下内容:
OK<float,double> ok;
float a = ok.GetRef<float>();
double b = ok.GetRef<double>();
Run Code Online (Sandbox Code Playgroud)
如果不专门化模板,则无法专门化类模板的成员模板.也就是说,要么提供完整的专业化T1并T2在类模板上修复,然后TX也可以修复或无法修复TX.
简单的解决方案不是专门化模板功能,而是提供不同的重载:
template<typename T1, typename T2>
class OK
{
T1 t1;
T2 t2;
public:
const T1& GetRef() const { return t1; }
template<typename TX> const TX & GetRef() const;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |