我想实现一个字符串类,它可以选择在堆栈或堆上创建内部缓冲区。所以我认为该字符串的外观如下:
String str_on_heap;
String<512> str_on_stack;
会很优雅。但是,后来我发现在C++中很难实现这样的接口(interface)。
template < int StackBufferSize = 0 >
class String {
... // Codes to implement String on stack.
};
template <>
class String< 0 > {
... // Codes to implement String on heap.
};
String str_on_heap; // Compile error, should be "String<> str_on_heap;"
String<512> str_on_stack; // OK.
有人有想法或其他 C++ 技巧来提供这样的接口(interface)吗?
最佳答案
如果String
类是一个模板,你总是需要使用<>
引用类时的符号。
您可以做的是为 StackBufferSize == 0
的情况编写一个模板专门化,它将使用堆。
template <int StackBufferSize = 0>
class String
{
// code to allocate string on the stack
};
template <>
class String<0>
{
// code to allocate on the heap
};
这样,当您声明 String<>
时它将使用堆的专门化。
也就是说,这可能不是一个好的设计决策。更好的解决方案可能是只使用 std::basic_string
如果您确实需要避免堆分配,请提供自定义分配器。
关于c++ - 在C++中,是否可以定义一个类用作: SomeObj obj1; SomeObj<4> obj2;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4416051/