Параметры шаблона, используемые в объявлении std :: vector - PullRequest
0 голосов
/ 13 февраля 2020

Я читаю о std::vector классе от здесь . и я немного запутался по поводу используемых параметров шаблона. Используемое объявление:

template<
    class T
    class Allocator = std::allocator<T> 
> class vector; 

Параметр class Allocator = std::allocator<T> сбивает меня с толку.

Это пример параметра шаблона шаблона ?

Я думаю, однако, он может вписаться в type-parameter-key name(optional) = default, то есть Type template parameter, который я найдено здесь .

Я попытался поэкспериментировать со следующим, но он дает ошибку компиляции:

значение d1 не может использоваться в константном выражении

#include<iostream>
#include<stdio.h>
#include<string>

using namespace std;

//Type template parameter
template<class T>
class foo{
    T a;
    public : 
    void sayHello(){
        cout<<"Say Hello to  : "<<a<<endl; //Would have taken care of the overloaading << , if there were no other errors
    }
    void  setVal(T temp){
        this->a = temp;
    }
};

class dog{
    string name ="labrador";
};

int main(){
dog d1;
//foo<d1> foo_1; ////Does not work
    return 0;
} 

Как заставить работать приведенный выше код?

1 Ответ

2 голосов
/ 13 февраля 2020

http://www.cplusplus.com/doc/oldtutorial/templates/ Приятель с простой синтаксической ошибкой, передает имя типа, а не идентификатор экземпляра типа. Для его компиляции я быстро реализовал перегрузку ostream.

#include<iostream>
#include<stdio.h>
#include<string>

using namespace std;

//Type template parameter
template<class T>
class foo{
    T a;
public :
    void sayHello(){
        cout<<"Say Hello to  : "<<a<<endl; //Would have taken care of the overloaading << , if there were no other errors
    }
    void  setVal(T temp){
        this->a = temp;
    }
};

class dog{
    string name ="labrador";
    friend ostream& operator<<(ostream& os, const dog& dt);
};

ostream& operator<<(ostream& os, const dog& dt)
{
    os << "dog stuff" << endl;
    return os;
}

int main(){
    dog d1;
    foo<dog> foo_1; ////Does not work
    foo_1.sayHello();
    return 0;
}
...