+ -
当前位置:首页 → 问答吧 → 类模版的疑问

类模版的疑问

时间:2011-12-12

来源:互联网

template <class Elem>
class Node{
Elem a;
public:
asd();//elem在int的情况下调用
asd();//Elem在char 的情况下调用
};

如上 加入在创建对象的时候 有可能Elem会取char int
我想在调用函数的时候 能根据类型自动核对asd函数 
能实现吗?

作者: xuminghui382   发布时间: 2011-12-12

template <class Elem>
class Node{
Elem a;
public:
template<typename T >//一个辅助函数模板。
__asd();
template<>
__asd<int>();//elem在int的情况下调用
__asd<char>();//Elem在char 的情况下调用

asd()//这是接口
{
return __asd<Elem>();
}
};

作者: mingliang1212   发布时间: 2011-12-12

__asd<char>();//Elem在char 的情况下调用


===
上面写错了一点,这个上面也要加上template<>

作者: mingliang1212   发布时间: 2011-12-12

template <class Elem>
class Node{
Elem a;
public:
asd() { __asd(a); };
private:
__asd(int);//elem在int的情况下调用
__asd(char);//Elem在char 的情况下调用
};

这样在调用的时候,就可以通过重载来指定了。
stl中也有这样的用法。

作者: yao_great   发布时间: 2011-12-12

楼上 我的意思asd里无参数 是根据对象类型自动核对

作者: xuminghui382   发布时间: 2011-12-12

楼主需要学习类模板的特化相关语法。
找本好点的教材吧,比如《C++ primer》

作者: taodm   发布时间: 2011-12-12

C/C++ code
#include<iostream>
using namespace std;

template <class Elem>
class Node{
    Elem a;
public:
    template<typename T >//一个辅助函数模板。
        asd();
    template<typename T >
    void asd<int>(){//elem在int的情况下调用
        cout<<"int";
    }
    template<typename T >
    void asd<char>(){cout<<"char";}//Elem在char 的情况下调用
    
    void asd()//这是接口
    {
        asd<Elem>();
    }
};

int main()
{
    Node<int> t1;
    t1.asd();
    Node<char> t2;
    t2.asd();
}


好多错误啊 指导一下呗 整不明白啊

作者: xuminghui382   发布时间: 2011-12-12

C/C++ code


template <class Elem>
class Node{
    Elem a;
public:
    template<typename T >//一个辅助函数模板。
     void/*少了返回类型*/  __asd();//名字要跟接口不同,说了是辅助的。。
    template<>
    void __asd<int>(){//elem在int的情况下调用
        cout<<"int";
    }
    template<>
    void __asd<char>(){cout<<"char";}//Elem在char 的情况下调用
    
    void asd()//这是接口
    {
        __asd<Elem>();
    }
};

int main()
{
    Node<int> t1;
    t1.asd();
    Node<char> t2;
    t2.asd();
}


作者: mingliang1212   发布时间: 2011-12-12