我试图使用自定义分配器std::vector<char>,但我注意到std::vector不需要/使用我的分配器中的任何成员函数.这怎么可能?
#include <vector>
struct A : private std::allocator<char> {
typedef std::allocator<char> alloc;
using alloc::value_type;
using alloc::pointer;
using alloc::const_pointer;
using alloc::difference_type;
using alloc::size_type;
using alloc::rebind;
// member functions have been removed, since the program compiles without them
};
int main() {
std::vector<char, A> v;
v.resize(4000);
for (auto& c : v)
if (c)
return 1; // never happens in my environment
return 0; // all elements initialized to 0. How is this possible?
}
Run Code Online (Sandbox Code Playgroud)
我正在使用在线C++ 11编译器(LiveWorkSpace)尝试上述程序,提供g ++ 4.7.2,4.8和4.6.3. …
我试图在命名空间内调用一个重载函数,并且有点挣扎.
工作示例1:没有命名空间
class C {};
inline void overloaded(int) {}
template<typename T> void try_it(T value) {
overloaded(value);
}
inline void overloaded(C) {}
int main()
{
try_it(1);
C c;
try_it(c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
工作示例2:模板之前定义的所有重载
class C {};
namespace n {
inline void overloaded(int) {}
inline void overloaded(C) {}
}
template<typename T> void try_it(T value) {
n::overloaded(value);
}
int main()
{
try_it(1);
C c;
try_it(c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
破坏的示例3:模板后的一些重载
class C {};
namespace n {
inline void overloaded(int) {}
}
template<typename T> void …Run Code Online (Sandbox Code Playgroud) 在c ++ 17之前,如果您有类似的分配器,则Allocator<typename, size_t>可以使用rebind结构。但是现在,在C ++ 17中,不推荐使用rebind结构。从中构造an的解决方案allocator<T,size_t>是allocator<T2, size_t>什么?