In C++,is it possible to define a class used as: SomeObj obj1; SomeObj<4> obj2;
I want to implement a string class which has an option to crea开发者_如何学编程te the inner buffer on stack or heap. So that I think about the appearance of that string like:
String str_on_heap;
String<512> str_on_stack;
will be elegant. But, latter I find that it is hard to implement such an interface in C++.
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.
Does any one has an idea or other C++ tricks to offer such an interface?
If the String
class is a template, you always need to use the <>
notation when referring to the class.
What you can do is write a template specialization for the case when StackBufferSize == 0
, which will use the heap.
template <int StackBufferSize = 0>
class String
{
// code to allocate string on the stack
};
template <>
class String<0>
{
// code to allocate on the heap
};
This way, when you declare String<>
it will use the specialization for the heap.
That said, this is probably not a good design decision. A better solution would probably be to just use std::basic_string
and provide a custom allocator if you really need to avoid heap allocations.
The syntax you want is, to my knowledge, impossible to obtain : you want String
to be simultaneously a class and a class template.
Just to provide an alternative to specialization on a given size, I believe you should take a look on Policy Based Design, and provide policies such as :
String<HeapStorage> heapStr;
String<StackStorage<512> > stackStr;
From my point of view, this is better design : better read, better understood without looking at the implementation, and does not rely on an 'invalid size' magic value.
Have you tried:
const int HEAP=-1;
template<> class String<HEAP> {
//... specialization for Heap
};
String<HEAP> str_on_heap;
精彩评论