This question already has answers here:
Container of fixed dynamic size
(4 answers)
Closed 7 years ago.
Is there a C++ type that acts like a "dynamically sized non resizable array"? This kind of type can be thought of as one of two things:
vector<T> but without resize, push_back, etc.
array<T,N> but where N is dynamic and not static.
I do not want a solution that only works if the type of the elements within the array is a non-copyable type. I want a generic solution.
Yes, there (pretty much) is. std::unique_ptr<T[]>. The primary template has a partial specialisation for this case, which provides the appropriate interface (operator [], no operator * etc.)
Alternatively, you can wrap std::vector in your own class and restrict its interface. You could even do that by deriving a class from std::vector using non-public inheritance and publishing only the relevant parts of its interface:
template <class T, class A = std::allocator<T>>
struct FixedVector : private std::vector<T, A>
{
using FixedVector::vector::vector;
using FixedVector::vector::operator=;
using FixedVector::vector::get_allocator;
using FixedVector::vector::at;
using FixedVector::vector::front;
using FixedVector::vector::back;
using FixedVector::vector::data;
using FixedVector::vector::begin;
using FixedVector::vector::cbegin;
using FixedVector::vector::end;
using FixedVector::vector::cend;
using FixedVector::vector::empty;
using FixedVector::vector::size;
using FixedVector::vector::operator[];
};
Related
This question already has answers here:
Can an unnamed struct be made static?
(2 answers)
Passing anonymous structures to functions as parameter using C++ [duplicate]
(3 answers)
Closed 9 months ago.
I'm writing an app in C++ that interfaces with some code written in C.
The following is a simplified version of a struct defined in C code that I can't modify.
struct event{
uint8_t type;
union {
struct /* WishThisHadAName */ {
// ...
} connect;
struct {
// ...
} disconnect;
};
};
I'm trying to be able to define functions that take a pointer to the different unnamed structs, connect, disconnect, and all the others not listed above. To look something like the following.
void onConnect( struct WishThisHadAName *evt );
Is it possible to create this prototype without modifying the original C struct? Is there an easy way to create a wrapper for the unnamed structs to give them a name? Am I forced to create named structs that mirror the unnamed ones I'm trying to use?
I know you can get the type of an instantiated variable with decltype but I can't figure out how I could use that or declval in order to create the function prototype I'm looking for.
Simple as using event_connect_t = decltype(event::connect);.
Then you can use it as void onConnect( event_connect_t *evt );.
You can't declare a compatible type, but you can just extract the existing type declaration from the definition. decltype can resolve static member references just fine.
If you're using a compiler such as gcc/g++, you can use typeof to create a typedef for the anonymous type:
typedef __typeof__(((struct event){0}).connect) conn_type;
typedef __typeof__(((struct event){0}).disconnect) disconn_type;
Or without compound literals:
struct event e;
typedef __typeof__(e.connect) t1;
typedef __typeof__(e.disconnect) t2;
This question already has answers here:
When should you use a class vs a struct in C++? [duplicate]
(27 answers)
Closed 1 year ago.
I have basic knowledge of structures from C, and as far as I'm aware, classes and structs are not exactly the same, but the c++ primer defines a "class" using the struct keyword starting on p. 72-73. Here's a small excerpt with the code:
"Defining the Sales_data Type
Although we can’t yet write our Sales_item class, we can write a more concrete class that groups the same data elements. Our strategy for using this class is that users will be able to access the data elements directly and must implement needed operations for themselves.Because our data structure does not support any operations, we’ll name our version Sales_data to distinguish it from Sales_item. We’ll define our class as follows:"
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
This book is suppose to be an authoritative overview of C++11, so why would they use the keyword struct instead of class to describe a class type?
It's common use to define POD types as struct and data types which contain other members, constructors, methods, etc. as class. They are basically the same, the difference being the members are public by default in a struct and private by default in a class.
The usage in the book is consistent with the above description.
This question already has answers here:
How to make my custom type to work with "range-based for loops"?
(10 answers)
Closed 4 years ago.
I've written a class vecMatrix that wraps around std::vector to provide two-dimensional storage functionalities. However, while it's incredibly convenient to be able to write loops that sweep the data in an std::vector object as
std::vector<float> vec;
for (auto& val: vec) { /* do stuff to val*/}
I can't do it with my custom class. What kind of operator overload is required to be able to code the same way for vecMatrix?:
vecMatrix<float> mat;
for (auto& val: mat) { /* do stuff to val*/}
You'll need to define member functions begin and end that return iterators to the range that your class represents (or you can define non members that take a reference to your class as arguments.
This question already has answers here:
When can I use a forward declaration?
(13 answers)
Closed 7 years ago.
I'm having a hard time understanding template class implementation in C++. I understand what a template class is and how to use it, but I cannot seem to implement them properly. This is for school so I cannot use standard library list/etc. I have made a template List class that acts as a linked list using a template node class. I have a third class bigInt which will be used to do infinite precision addition, multiplication, etc. For the bigInt class I get an error when trying to have a variable "values" that is of type List. Why is this? Error: "Error C2079 'bigInt::values' uses undefined class 'List'"
bigInt.h looks like:
template <typename T>
class List;
class bigInt {
public:
List<int> values;
bigInt();
bigInt add(bigInt);
bigInt mul(bigInt);
bigInt pow(int);
};
I added the first two lines because I read somewhere that I needed to use "forward declaration" (since you apparently cannot use an #include "List.h") which I also don't really understand.
Any help would be really appreciated.
You need to completely define the class List<> before you can use it as a member variable. This is usually done by defining the template class in a separate .h file and #includeing it where needed (not sure why you think you can't do this). Alternatively, you can use a pointer to a List without defining it first:
template <typename T>
class List;
class bigInt {
public:
List<int>* values;
/*...*/
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic dispatching of template functions?
I would like to use non-type templates to create grid cells with different memory footprints without having to use dynamically allocated memory on the heap, e.g.
template <int cell_size>
class myCell {...}
There is a finite number of cell sizes (approx. 10), thus I can easily instantiate all of them explicitly. However, which one of the cells are needed is not known at compile time but during runtime only.
I know that templates are a compile-time concept, but is there a way to use templated classes in this way, especially since I can guarantee that all necessary cell types are explicitly instantiated?
You can use factory pattern, but you'll need a base class as a return type:
template <int cell_size>
class myCell : public cellBase {...}
struct CellFactory
{
static cellBase* getCell(int cell_size)
{
switch (cell_size)
{
case 1:
return new myCell<1>;
break;
//and so on
}
}
}
This works because you're telling the compiler which specializations it can expect. But I think that a better design exists for the underlying problem you're trying to solve.