c ++模板部分专业化成员函数 [英] c++ template partial specialization member function

查看:84
本文介绍了c ++模板部分专业化成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的模板,所以也许这是一个琐碎的事情,但我不能得到它的工作。我试图得到一个类成员函数的部分专门化。最短的代码是:

  template< typename T,int nValue> class Object {
private:
T m_t;
Object();
public:
Object(T t):m_t(t){}
T Get(){return m_t; }
Object& Deform(){
m_t * = nValue;
return * this;
}
};

template< typename T>
Object< T,0>& Object< T,0> :: Deform(){
this-> m_t = -1;
return * this;
}

int main(){
Object< int,7> nObj(1);
nObj.Deform();
std :: cout<< nObj.Get();
}

我尝试使用非成员函数,



但是,每当我尝试部分规范。的成员函数我得到的形式的错误:

  PartialSpecification_MemberFu.cpp(17):错误:模板参数
列表必须匹配参数列表对象< T,0>& Object< T,0> :: Deform()。不喜欢任何帮助: - )

>解决方案

你不能只部分专门化一个成员函数,你必须部分专业化整个类。因此,你需要像下面这样:

  template< typename T& 
class Object< T,0>
{
private:
T m_t;
Object();
public:
Object(T t):m_t(t){}
T Get(){return m_t; }
Object& Deform()
{
std :: cout< Spec\\\
;
m_t = -1;
return * this;
}
};


I'm new to templates so maybe this is a trivial thing but I cannot get it to work. I'm trying to get partial specialization of a class member function. The shortest code would be:

template <typename T, int nValue> class Object{
private:
    T m_t;
    Object();
public:
    Object(T t): m_t(t) {}
    T Get() { return m_t; } 
    Object& Deform(){ 
        m_t*=nValue; 
        return *this;
    }
};

template <typename T>
Object<T,0>& Object<T,0>::Deform(){
    this->m_t = -1;
    return *this;
}

int main(){
    Object<int,7> nObj(1);
    nObj.Deform();
    std::cout<<nObj.Get();
}

I tried with nonmember functions and that's worked fine. What also works fine is full specialization of a member function.

But, whenever I try with partial spec. of a member function I get error of the form:

PartialSpecification_MemberFu.cpp(17): error: template argument
list must match the parameter list Object<T,0>& Object<T,0>::Deform().

Would appreciate any help :-)

解决方案

You cannot partially specialize only a single member function, you must partially specialize the whole class. Hence you'll need something like:

template <typename T>
class Object<T, 0>
{
private:
    T m_t;
    Object();
public:
    Object(T t): m_t(t) {}
    T Get() { return m_t; } 
    Object& Deform()
    {
        std::cout << "Spec\n";
        m_t = -1;
        return *this;
    }
};

这篇关于c ++模板部分专业化成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆