2010-11-15 76 views
3

我们可以在没有模板类的普通类中声明template函数,还是应该总是在template class之内?C++中的模板

+0

我认为你的意思是“班级模板”。一个类模板,比如'template struct Foo {};'是一种模板,但不是一种类。同样,“功能模板”是另一种模板,而不是功能。 – MSalters 2010-11-15 09:56:18

+0

这已经是一个骗局 – 2010-11-15 13:23:28

回答

2

我们可以在一个普通的类声明模板函数同出一模板类

我们可以。例如

class demo 
{ 
    public: 
    template <typename T> 
    void func(const T& x) { 
     //do stuffs 
    } 
}; 

int main() 
{ 
    demo d; 
    d.func<int>(5); 
} 

是完全有效

2

是的,你可以在非模板类模板函数的支持,例如:

struct X { 
    template<class T> 
    void f(const T& t) { 
     // ... 
    } 
}; 
0

是的,你可以,但要确保你的定义和模板函数的声明是在头文件。如果你想知道更多为什么这样或更多关于模板一般我可以推荐你这本书Templates - Complete Guide