标准说,如果没有人能分辨出区别,你就可以侥幸逃脱。并且您是正确的,不能合法地将 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
成员函数是否为静态打印出“静态”或“非静态”。