【问题标题】:Template parameters used in std::vector declarationstd::vector 声明中使用的模板参数
【发布时间】:2020-02-13 00:56:35
【问题描述】:

我正在阅读来自here 的std::vector 课程。我对使用的模板参数有点困惑。使用的声明是:

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

参数class Allocator = std::allocator&lt;T&gt; 让我很困惑。

这是模板模板参数的例子吗?

不过,我认为它可能适合type-parameter-key name(optional) = default,即Type template parameter,我找到了here。

我尝试了以下实验,但它给出了编译错误:

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;
} 

我怎样才能使上面的代码工作?

【问题讨论】:

  • 模板参数必须在编译时知道。 d1 是在运行时创建的对象实例。您需要将foo&lt;d1&gt; 更改为foo&lt;dog&gt; 或foo&lt;decltype(d1)&gt;,因为foo 期望它的T 参数是一个类型,而不是一个变量。
  • 你的样本无论如何都不会工作,直到你为dog类型重载operator&lt;&lt;。是的,实例化应该是foo&lt;dog&gt;。
  • 不,这不是“模板模板参数”。
  • 这是模板模板参数的例子吗? 不是。模板模板参数是指模板参数,模板参数本身就是模板的名称。 (真是满口模板)
  • 我看不出代码与上面关于std::vector 模板参数的问题有什么关系。你能澄清一下吗?但是你的第二个猜测是正确的:Allocator 参数是一个带有默认参数的类型模板参数。

标签: c++ templates c++14


【解决方案1】:

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;
}

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多