实例化模板函数时出现奇怪错误

Weird error when instantiating template function

本文关键字:错误 函数 实例化      更新时间:2023-10-16

我有以下模板函数:

template <std::size_t first, std::size_t last, typename T>
bool in_range(T& in)
{
    for(auto i = in.begin(); i!=in.end(); ++i)
        if(*i<first || *i>last)
            return false;
    return true;
}

但当我尝试这样使用它时:

std::vector<int> test;
test.push_back(1);
test.push_back(5);
test.push_back(6);
std::cout<<in_range<4,7>(test);

我得到一个奇怪的错误:

main.cpp: In instantiation of 'bool in_range(T&) [with long long unsigned int first = 4ull; long long unsigned int last = 7ull; T = std::vector<int>]':
main.cpp:31:34:   required from here

我做错了什么?

编辑:完整生成日志:http://pastebin.com/Cwemq2Hk

如果我在启用C++11支持的情况下构建它,那么它就会编译。这是一个演示。

在C++11之前,auto有不同的含义,因此auto i = ...是无效的——它声明了一个没有类型的变量。

我猜你使用的是GCC;根据版本的不同,您需要指定-std=c++0x-std=c++11作为命令行选项。