Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何根据类专门化模板成员函数';模板参数?_C++_Templates_Template Specialization - Fatal编程技术网

C++ 如何根据类专门化模板成员函数';模板参数?

C++ 如何根据类专门化模板成员函数';模板参数?,c++,templates,template-specialization,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>::GetR

我想这样写:

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

如果不专门化模板,则不能专门化类模板的成员模板。也就是说,您可以提供一个完整的专门化,在类模板上固定
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;
};
模板
类OK
{
T1;
T2;
公众:
常量T1&GetRef()常量{return T1;}
模板常量TX&GetRef()常量;
};

我明白了。我想我不能为t2提供一个getter,也就是GetRef。@Gabriel:不。。。我想我真的不太明白您想要做什么,但是为什么不提供两个不同的函数来返回每个成员呢?如果您想要的是一个基于类型返回任一选项的
GetRef
,那么您可以添加一个额外的间接级别来解析它:
template T const&get()const{return get((T*)0);};T1 const&get(T1*){return T1;}T2 const&get(T2*){return T2;}
其中两个非模板
get
将是私有的。很好!这就成功了!(顺便说一句,你忘了带警察了)谢谢你!
OK<float,double> ok;
float a = ok.GetRef<float>();
double b = ok.GetRef<double>();
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;
};