c++ - 在C++中,是否可以定义一个类用作: SomeObj obj1; SomeObj<4> obj2;

标签 c++ templates macros

我想实现一个字符串类,它可以选择在堆栈或堆上创建内部缓冲区。所以我认为该字符串的外观如下:

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/

相关文章:

c++ - 使用指针表示法访问结构数组

c++ - 成员函数调用和C++对象模型

c++ - 不明确的模板参数

grails - 有没有办法做 gsp partials 而不是标签库?

c++ - Boost multiprecision 失败,因为 complex 的实现试图在 _Isinf 或 _Isnan 等内部函数中转换为 double

android - 如何通过trace调试android原生crash?

json - 我的 Django View 如何知道要呈现哪个模板,或者是否返回 JSON?

c++ - 从非模板化接口(interface)检索 'generic'数据

c++ - 产生可疑错误的宏

macros - 如何在qlikview中使用宏