c ++编译器如何知道参数是STL容器?

Dav*_*way 1 c++ intellisense templates

c ++ newbie question - C++编译器如何知道模板函数的参数是否具有STL方法作为成员?在C#中,您告诉一个泛型方法,参数具有类型约束,最常见.它必须实现一个接口,但对于c ++模板,参数类型没有限制.

#include <list>
#include <iostream>
using namespace std;
template <typename T>
void DisplayContents (const T& Input)
{
    for (auto iElement = Input.cbegin() // no intellisense
    ; iElement != Input.cend()
    ; ++ iElement )
    cout << *iElement << ' ';

    cout << endl;
}
int main ()
{
    std::list <int> listIntegers;
    listIntegers.push_front (10);
    listIntegers.push_front (2011);
    listIntegers.push_back (-1);
    listIntegers.push_back (9999);
    DisplayContents(listIntegers);
    //  DisplayContents(99); // neither of these will compile
    //  DisplayContents(new string("")); //
return 0;
}
Run Code Online (Sandbox Code Playgroud)

因此,在模板化方法DisplayContents <>(const T&Input)中,Input上没有intellisense.当您键入句点字符时,不会弹出任何建议(这并不令人惊讶,因为函数参数未指定输入必须是列表或任何其他类型的STL容器).

但是,如果您尝试将不是STL容器的内容发送到DisplayContents <>(const T&Input),则编译器会抛出这些错误: -

  • 错误C2100:非法间接
  • 错误C2228:'.cbegin'的左边必须有class/struct/union
  • 错误C3536:'iElement':在初始化之前无法使用

建议编译器确实知道需要具有一些基本特征的参数类型.

任何人都可以解释一下编译器如何"知道"当列表作为参数发送时可以使用cbegin()和*运算符,但是当发送字符串或int时则不会,当显然类型不知道为intellisense时是不是拿起了方法cbegin()?

cdh*_*wie 6

真的很简单.编译器将假装这T是您传入的参数类型,然后继续编译.如果它遇到任何错误,那么它将报告这些错误.只要你使用参数的类型会,如果你硬编码的那种类型工作,那么它会工作.

在你的情况下,它失败了int因为int没有cbegin()方法.

它失败了,new std::string("")因为参数类型变为std::string * const &,并且您无法调用.cbegin()此指针.(你必须打电话->cbegin().)

但是,您可以调用它std::string("")(注意缺少new)将导致参数const std::string &,并且这将编译.

因此它与编译器"知道T代表一个标准容器" 没有任何关系.如果使用cbegin()和cend()方法创建一个简单类型,并确保这些方法的返回值可以递增,取消引用并进行相等性比较,那么该类型也可以正常工作.

(这是使用用户定义类型的模板函数的演示.)