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.
Related
This question already has answers here:
What are the differences between struct and class in C++?
(30 answers)
Closed 1 year ago.
In C++, I'm trying to decide whether or not to use a struct or class. So far I understand that both are more or less identical, but a class is used more often when private variables are needed or to group the concept of an object that performs actions.
But what I'm wondering is: Does including functions within a class increase the memory requirements (as opposed to having structs, with functions separated)?
Here is an example
class Vector2D {
public:
int x;
int y;
Vector2D();
getMagnitude();
Normalize();
}
vs.
struct Vector2D {
int x;
int y;
}
// Some functions defined separately
getMagnitude(Vector2D v);
Normalize(Vector2D v);
And if I have a bunch of other vector functions, say, adding two of them together and I have a vector class, is it better if those are included in the class, so you have a function like addToVector(Vector2D v2) or to keep these multi vector functions outside of the class so that you'd have an addToVector(Vector2D v, Vector2D v2)?
I understand the second question might lean towards opinion, but if there is a "best practice" defined way, I'd like to know.
Thank you
C++ Efficiency of Classes vs Structs
Structs are classes. There is zero efficiency between one and the other.
Does including functions within a class increase the memory requirements (as opposed to having structs, with functions separated)?
No. There is no practical difference between "memory requirements" of member functions and non-member functions.
Also, structs can have member functions. All classes can have member functions, and structs are classes.
This question already has answers here:
Check if class is derived from a specific class (compile, runtime both answers available)
(6 answers)
Closed 3 years ago.
Suppose I'm writing the following templated function:
class A { /* ... */ };
// ... etc...
template<typename C>
void foo() {
bool C_inherits_A = /* magic */;
if (C_inherits_A) { do_something(); }
else { do_something_else(); }
}
We remember dynamic_cast from the olden days, but that isn't relevant here since there's no pointer, and I'm checking "downward", not "upward". Is there something simple with which to replace /* magic */ in the snippet above?
PS - There should definitely already be a dupe of this question, but I just could not find one so I wrote it up.
Beginning in C++11, the standard C++ library caters to this exact need - using the std::is_base_of type trait. To read a bit more about type traits see their SO tag page.
Anyway, you would replace /* magic */ with:
std::is_base_of<A, C>::value
which is a Boolean expression that's true if A is a base class of C, i.e. if C inherits A.
Remember that type traits are evaluated at compile-time, so you can use if (std::is_base_of<A,C>::value) in constexpr functions, or in template parameters and so on.
This question already has answers here:
Can I implement an autonomous `self` member type in C++?
(14 answers)
Closed 7 years ago.
I want to write a macro which, when expanded within a class, uses that class type (specifically, as template argument). Within class method, I can use this:
#define METHOD_MACRO int sample_method(void)const {\
return template_struct<this_type<decltype(this)>::type>::index;}
(this_type is my struct, here it's equivalent to remove_pointer<remove_const<T>>)
But when I need class type outside of method (for typedef for class member pointer), this keyword isn't available; I've tried to use auto for some trick with deducing type, but no luck here.
Classes in question are inherited from my class, if this can be of any help. I would like to avoid anyone using my macro having to write obligatory typdedef.
Any ideas?
You can use the following trick:
#define SELF \
static auto helper() -> std::remove_reference<decltype(*this)>::type; \
typedef decltype(helper()) self
struct A {
SELF;
};
I declare a helper function using the auto return type, which allows me to use decltype(*this) as a return type, not knowing what is the class name. Then I can use decltype(helper()) to use the class type in the code. Note that the function has to be static, otherwise you can not use it in decltype. Also the function is just declared, not defined; this should not be a problem as you are not going to call it anyway. (You can add an empty body to it, but it will raise a warning that a function has no return. Still you may change the return type to be decltype(this) and return nullptr.)
You may then use the self typedef for further declarations, or just alter the macros to typedef not the class itself, but what you need to. Adjust it to suit your particular need.
UPD: This seems to be a non-standard behavior of GCC. For example, ICC does not allow this in static functions even in trailing return type.
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[];
};
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Template type deduction in C++ for Class vs Function?
When calling a template function, you don't need to specify the template parameters if they are non-ambiguous from your parameters. E.g. for:
template<typename T> T foo(T a) { /*...*/ }
You can just call foo(1) and it will work, it does not need to be foo<int>(1).
This is not true for classes/structs, even if it would be clear from the constructor parameters. For example:
template<typename T> struct Foo { Foo(T a) { /*...*/ } };
Now I cannot do just a do_something_with(Foo(1)), it must be do_something_with(Foo<int>(1)).
Often, to work around this issue, there are just some simple wrapper functions which basically just wrap the constructor. That is even in the STL: std::make_pair is such an example.
Now the question: Why is that? Is there any rational reason behind it?
As far as I know, function templates and class templates are different for the lulz and there's no real reason that they should be different from each other. Of course, class templates have partial specializations (T*) as an advantage.