[英]How to specialize a template constructor templated?
How do I make the specialization on a template constructor? 如何在模板构造函数上进行特化? For the purpose of better understandings, I will bring an example of code:
为了更好的理解,我将带来一个代码示例:
template<typename T>
class Stack {
private:
int nelem;
int size;
vector<T> stack;
public:
~Stack();
Stack<T>(int t);
void push(T data);
T pop();
T top();
int getPosTop(){return (nelem--);};
void cleanStack(){nelem = 0;};
bool StackEmpty(){ return (nelem == 0);};
bool StackFull(){ return (nelem == size);};
};
template <typename T> // constructor definition here
Stack<T>::Stack<T>(int t){
size = t;
nelem = 0;
};
int main(){
return 0;
}
It came with lots of errors. 它带来了很多错误。 Then, I read on another post, some suggestion , which was replacing
然后,我读了另一篇文章,一些建议,正在取代
template <typename T>
Stack<T>::Stack<T>(int t){
to 至
template <typename T> template <typename T> Stack<T>::Stack<T> (int t){
Which was not sufficient. 这还不够。
What am I missing? 我错过了什么? And, what is the thinking behind it?
而且,背后的想法是什么?
Only your class is template, not your constructor, you should simply use 只有你的类是模板,而不是你的构造函数,你应该只使用
template <typename T>
Stack<T>::Stack(int t){ /*...*/ }
If you want to specialize your constructor for Stack<char>
, it would be 如果你想专门为
Stack<char>
构造函数,那就是
template <>
Stack<char>::Stack(int t){ /*...*/ }
You want to know how to specialize just the constructor Stack<T>::Stack
for particular values of T
. 您想知道如何专门为
T
特定值构造函数Stack<T>::Stack
。 You do it as illustrated:- 你按照说明这样做: -
#include <vector>
#include <iostream>
template<typename T>
class Stack {
private:
std::size_t nelem;
std::size_t size;
std::vector<T> stack;
public:
~Stack(){};
Stack<T>(std::size_t n);
void push(T data);
T pop();
T top();
std::size_t getPosTop(){return (nelem--);};
void cleanStack(){nelem = 0;};
bool StackEmpty(){ return (nelem == 0);};
bool StackFull(){ return (nelem == size);};
};
template <typename T>
Stack<T>::Stack(std::size_t t){
size = t;
nelem = 0;
std::cout << "Constructing a `Stack<T>`\n";
}
template <>
Stack<std::string>::Stack(std::size_t t){
size = t;
nelem = 0;
std::cout << "Constructing a `Stack<T>` with `T` = `std::string`\n";
}
template <>
Stack<int>::Stack(std::size_t t){
size = t;
nelem = 0;
std::cout << "Constructing a `Stack<T>` with `T` = `int`\n";
}
int main() {
Stack<float> sf{2};
Stack<int> si{3};
Stack<std::string> ss{4};
sf.cleanStack();
si.cleanStack();
ss.cleanStack();
return 0;
}
Which outputs:- 哪些产出: -
Constructing a `Stack<T>`
Constructing a `Stack<T>` with `T` == `int`
Constructing a `Stack<T>` with `T` == `std::string`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.