c++ - How to specialize a template constructor templated? -


how make specialization on template constructor? purpose of better understandings, bring 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 lots of errors. then, read on post, suggestion , replacing

template <typename t>     stack<t>::stack<t>(int t){ 

to

template <typename t> template <typename t> stack<t>::stack<t> (int t){ 

which not sufficient.

what missing? and, thinking behind it?

you want know how specialize constructor stack<t>::stack particular values of t. 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 `stack<t>`\n"; }  template <> stack<std::string>::stack(std::size_t t){     size = t;     nelem = 0;     std::cout << "constructing `stack<t>` `t` = `std::string`\n"; }  template <> stack<int>::stack(std::size_t t){     size = t;     nelem = 0;     std::cout << "constructing `stack<t>` `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 `stack<t>` constructing `stack<t>` `t` == `int` constructing `stack<t>` `t` == `std::string` 

live demo


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -