我正在编写一种容器类,我想提供一种apply方法来评估容器内容的函数.
template<typename T>
struct Foo
{
T val;
/** apply a free function */
template<typename U> Foo<U> apply(U(*fun)(const T&))
{
return Foo<U>(fun(val));
}
/** apply a member function */
template<typename U> Foo<U> apply(U (T::*fun)() const)
{
return Foo<U>((val.*fun)());
}
};
struct Bar{};
template class Foo<Bar>; // this compiles
//template class Foo<int>; // this produces an error
Run Code Online (Sandbox Code Playgroud)
最后一行产生error: creating pointer to member function of non-class type ‘const int’.虽然我只实例化Foo,而不是用apply在所有.所以我的问题是:如果T是非类型类型,我怎样才能有效地删除第二个重载?
注意:我也试过只有一个重载 …
代码如下
std::vector<int> a;
for(size_t i = 0; i < n; ++i)
a.push_back(0);
Run Code Online (Sandbox Code Playgroud)
保证在线性时间内运行n。这是通过在重新分配时分配一些额外的备用容量来实现的(通常将总容量增加一个常数因子)。
但是关于std::vector::insert(pos, x)?即是否保证
std::vector<int> a;
for(size_t i = 0; i < n; ++i)
a.insert(a.end(), 0);
Run Code Online (Sandbox Code Playgroud)
也是线性的吗?(类似的问题insert(pos, first, last)当然适用)
文档清楚地保证了“摊销常数”的复杂性。push_back
但文档insert说复杂性应该是“常数加上 pos 和容器末端之间距离的线性”。显然,只有在没有发生重新分配的情况下,这才是正确的,因此我不确定。
编辑:答案摘要:当发生重新分配时,实现可以
在 的情况下push_back,本质上需要选项 (2) 来实现“摊余常数”运行时间。在 的情况下insert(pos, first, last),在单遍 InputIterator 的情况下需要选项 (2)(但在多遍 ForwardIterator 的情况下,实现可以并且确实使用 的单次重新分配new_capacity = max(2*old_capacity, new_size))。所有其他情况均由实现定义。
使用 GCC 11 和 clang 12 进行测试,情况似乎是:
reserve并 …