为什么我不能为<map> type?</map>的函数参数设置默认值

时间:2014-04-09 02:05:53

标签: c++

以下是我不能编译的示例程序。我想创建一个将map作为可能的参数的函数,但是如果没有提供,则提供默认的空映射。非常直接,只是不确定为什么它不起作用。

#include <map>
#include <iostream>
using std::cout; using std::endl; using std::map;

int func(map<int, int>& = map<int, int>());

int main() {
    map<int, int> m;
    m[2] = 4;

    cout << "func() = " << func() << endl;   // "func() = 0"
    cout << "func(m) = " << func(m) << endl; // "func(m) = 1"
}

int func(map<int, int>& m) { return m.size(); }

我得到的编译错误是:

test.cc:6:42: error: default argument for 'std::map<int, int>& <anonymous>' has type 'std::map<int, int>'

请解释,这对我没有意义。

1 个答案:

答案 0 :(得分:1)

您可以使用常量引用绑定临时对象。因此该函数可能被声明为

int func( const map<int, int>& = map<int, int>());
相关问题