繁体   English   中英

如何根据类的模板参数来专门化模板成员函数?

[英]How to specialize a template member function depending on the class' template arguments?

我想写这个:

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

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

我错过了什么? 我甚至想做什么?

编辑 :我想拥有所有字段的getter,都叫做GetRef() ,所以用户可以这样写:

OK<float,double> ok;
float a = ok.GetRef<float>();
double b = ok.GetRef<double>();

如果不专门化模板,则无法专门化类模板的成员模板。 也就是说,要么提供完整的专业化, T1T2固定在类模板上,然后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;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM