9

std::forward_list提供insert_aftererase_after可能不需要实际访问std::forward_list对象的成员。因此,它们可以实现为static成员函数,并且可以在没有列表对象的情况下调用——这对于想要从列表中删除自身的对象很有用,这是一种非常常见的用途。编辑:此优化仅适用于forward_list专业化std::allocator或用户定义的无状态分配器。

符合标准的实现可以做到这一点吗?

§17.6.5.5/3 说

对 C++ 标准库中描述的成员函数签名的调用表现得好像实现声明没有其他成员函数签名一样。

带脚注

一个有效的 C++ 程序总是调用预期的库成员函数,或具有等效行为的函数。实现还可以定义其他成员函数,否则这些成员函数不会被有效的 C++ 程序调用。

我不清楚添加是否static会创建一个“不同的”成员函数,但是删除(隐式)参数不应该破坏添加默认参数不会破坏的任何内容,这是合法的。(您不能合法地将 PTMF 带入任何标准成员函数。)

我觉得应该允许图书馆这样做,但我不确定是否会违反某些规则。列出的成员函数原型有多规范?

4

1 回答 1

9

标准说,如果没有人能分辨出区别,你就可以侥幸逃脱。并且您是正确的,不能合法地将 PTMF 创建到forward_list中,因此您是安全的。

已经指出了自定义分配器的危险。但即使std::allocator<T>存在有人可以专门std::allocator<MyType>化然后检测到allocator::construct/destroy没有被调用的危险。

好的,但是可以专门说std::forward_list<int>(没有自定义分配器,没有用户定义的 value_type)并将其设为insert_after静态吗?

不会。可以通过新的 SFINAE 功能检测到此更改。这是一个演示:

#include <memory>
#include <iostream>

template <class T, class A = std::allocator<T>>
class forward_list
{
public:
    typedef T value_type;
    struct const_iterator {};
    struct iterator {};

    iterator insert_after(const_iterator p, const T& x);
};

template <class C>
auto test(C& c, typename C::const_iterator p, const typename C::value_type& x)
    -> decltype(C::insert_after(p, x))
{
    std::cout << "static\n";
    return typename C::iterator();
}

template <class C>
auto test(C& c, typename C::const_iterator p, const typename C::value_type& x)
    -> decltype(c.insert_after(p, x))
{
    std::cout << "not static\n";
    return typename C::iterator();
}

int main()
{
    ::forward_list<int> c;
    test(c, ::forward_list<int>::const_iterator(), 0);
}

该程序运行并打印出:

not static

但是,如果我制作insert_after静态:

static iterator insert_after(const_iterator p, const T& x);

然后我得到一个编译时错误:

test.cpp:34:5: error: call to 'test' is ambiguous
    test(c, ::forward_list<int>::const_iterator(), 0);
    ^~~~
test.cpp:16:6: note: candidate function [with C = forward_list<int, std::__1::allocator<int> >]
auto test(C& c, typename C::const_iterator p, const typename C::value_type& x)
     ^
test.cpp:24:6: note: candidate function [with C = forward_list<int, std::__1::allocator<int> >]
auto test(C& c, typename C::const_iterator p, const typename C::value_type& x)
     ^
1 error generated.

检测到差异。

forward_list::insert_after因此,将其设为静态是不合格的。

更新

如果您想让“静态”重载可调用,您只需使其比“非静态”重载更可取。一种方法是将“非静态”重载更改为:

template <class C, class ...Args>
auto test(C& c, typename C::const_iterator p, const typename C::value_type& x, Args...)
    -> decltype(c.insert_after(p, x))
{
    std::cout << "not static\n";
    return typename C::iterator();
}

现在测试将根据insert_after成员函数是否为静态打印出“静态”或“非静态”。

于 2011-10-19T16:51:56.330 回答