I want a class template template<std::size_t N> Shape, where the template parameter N represents the dimension of the Shape. There should be a limited number of predefined Shapes, such as Shape<2> SQUARE, Shape<3> CUBE and Shape<3> SPHERE. I might add more predefined Shapes in the future.
I want Shape objects only to be constructible as any of the predefined Shapes. Since the properties of these predefined Shapes remain the same at all time, it would be optimal to have them stored only once, and to have new Shape objects refer to them.
At this moment, I have the following implementation:
// Flag for the possible shapes
enum class Tag
{
SPHERE,
CUBE,
SQUARE
};
template<std::size_t N>
class Shape
{
public:
// Predefined shapes.
static const Shape<3> SPHERE;
static const Shape<3> CUBE;
static const Shape<2> SQUARE;
// Information stored about the given shapes
const Tag tag; // tag specifying the shape
const double v; // Shape volume/area
const std::array<double, 2*N> surrounding_box; // Storing intervals for a surrounding box
//... Some other information that depends on template parameter N
private:
// Private constructor. This prevents other, unintended shapes from being created
Shape(Tag tag, double v, const std::array<double, 2*N> surrounding_box):
tag{tag}, v {v}, surrounding_box {surrounding_box} {};
};
// Initialization of predefined shape: SPHERE
template<std::size_t N>
const Shape<3> Shape<N>::SPHERE(Tag::SPHERE, 3.0,{{0.0,2.7,0.0,2.7,0.0,2.7}});
// Initialization of predefined shape: CUBE
template<std::size_t N>
const Shape<3> Shape<N>::CUBE(Tag::CUBE, 1.0,{{0.0,1.0,0.0,1.0,0.0,1.0}});
// Initialization of predefined shape: SQUARE
template<std::size_t N>
const Shape<2> Shape<N>::SQUARE(Tag::SQUARE, 1.0,{{0.0,1.0,0.0,1.0}});
This implementation has a few problems:
Every instance of Shape contains all the predefined Shapes (As pointed out in the comments of this question);
Fore every instance of Shape that is created, the content of the predefined Shapes gets copied;
Even a Shape<3> object contains the Shape<2> SQUARE.
...
I would like to know what would be a better design pattern to achieve the above described goals.
I was thinking of using the Tag as a constructor parameter and using some kind of factory. However, I have problems to get the implementation details right due to the template complications and the fact that I only want predefined Shapes to be constructible.
Factory pattern is what you need. It delegates the creation of the instances to another class.
There are multiple way to implement it, you can choose the level of abstraction depending on the complexity of your problem.
Here's a basic example
template<std::size_t N>
class Shape
{
friend class ShapeFactory;
public:
// Information stored about the given shapes
const Tag tag; // tag specifying the shape
const double v; // Shape volume/area
const std::array<double, 2*N> surrounding_box; // Storing intervals for a surrounding box
//... Some other information that depends on template parameter N
private:
// Private constructor. This prevents other, unintended shapes from being created
Shape(Tag tag, double v, const std::array<double, 2*N> surrounding_box):
tag{tag}, v {v}, surrounding_box {surrounding_box} {};
};
class ShapeFactory
{
public:
// return value optimization
static Shape<3> createSphere()
{
return Shape<3>(Tag::SPHERE, 3.0,{{0.0,2.7,0.0,2.7,0.0,2.7}});
}
static Shape<3> createCube()
{
return Shape<3>(Tag::CUBE, 1.0,{{0.0,1.0,0.0,1.0,0.0,1.0}});
}
static Shape<2> createSquare()
{
return Shape<2>(Tag::SQUARE, 1.0,{{0.0,1.0,0.0,1.0}});
}
};
Since the properties of these predefined Shapes remain the same at all
time, it would be optimal to have them stored only once, and to have
new Shape objects refer to them.
if you strictly want to use this approach, you can refer to Prototype Pattern
Related
In a C++/CX class I want to create a DependencyProperty that gets or sets a normal C++ float value type but I just cannot figure out how I need to specify the type that is expected by the DependencyProperty::Register.
Let me make an example. If I were to use a property that works with a reference type I'd put the following into the header file of my C++/CX class:
public:
static property Windows::UI::Xaml::DependencyProperty^ BackgroundColorProperty
{
Windows::UI::Xaml::DependencyProperty^ get();
};
property Windows::UI::Xaml::Media::Brush^ BackgroundColor
{
Windows::UI::Xaml::Media::Brush^ get();
void set(Windows::UI::Xaml::Media::Brush^ value);
};
private:
static Windows::UI::Xaml::DependencyProperty^ _backgroundColorProperty;
static void OnBackgroundColorChanged(Windows::UI::Xaml::DependencyObject^ d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
The implementation would look like this:
DependencyProperty^ MyCustomClass::BackgroundColorProperty::get()
{
return _backgroundColorProperty;
}
Windows::UI::Xaml::Media::Brush^ MyCustomClass::BackgroundColor::get()
{
return static_cast<Windows::UI::Xaml::Media::Brush^>(GetValue(BackgroundColorProperty));
}
void MyCustomClass::BackgroundColor::set(Windows::UI::Xaml::Media::Brush^ value)
{
SetValue(BackgroundColorProperty, value);
}
DependencyProperty^ MyCustomClass::_backgroundColorProperty =
DependencyProperty::Register("BackgroundColor",
Brush::typeid,
MyCustomClass::typeid,
ref new PropertyMetadata(ref new SolidColorBrush(Windows::UI::ColorHelper::FromArgb(255, 255, 255, 255)), ref new PropertyChangedCallback(&MyCustomClass::OnBackgroundColorChanged)));
void MyCustomClass::OnBackgroundColorChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
MyCustomClass^ myClass = static_cast<MyCustomClass^>(d);
// Do whatever needs to be done
}
This all works. Visual Studio's XAML Designer recognizes that property and everything works as expected.
But lets say I want a property that uses a float instead of the Brush. How would I need to specify the necessary type in the DependencyProperty::Register method? I mean the second argument in the code below.
DependencyProperty^ MyCustomClass::_backgroundColorProperty =
DependencyProperty::Register("BackgroundColor",
/* How do I specify the type of the float here?*/,
MyCustomClass::typeid,
ref new PropertyMetadata(1.0f, ref new PropertyChangedCallback(&MyCustomClass::OnBackgroundColorChanged)));
I have tried the following which didn't work:
ref new TypeKind(TypeKind::Primitive, float32)
typeof(float32)
typeof(float)
typeid(float)
ref new Windows::UI::Xaml::Interop::TypeKind(TypeKind::Primitive, float)
ref new Windows::UI::Xaml::Interop::TypeKind(TypeKind::Primitive, typeid(float))
You can directly use float::typeid to register float type.
DependencyProperty^ MyCustomClass::_backgroundColorProperty =
DependencyProperty::Register("BackgroundColor",
float::typeid,
MyCustomClass::typeid,
ref new PropertyMetadata(1.0f, ref new PropertyChangedCallback(&MyCustomClass::OnBackgroundColorChanged)));
In addition, from this document, it mentions:
If you want a DP with a floating-point type, then make it double
(Double in MIDL 3.0). Declaring and implementing a DP of type float
(Single in MIDL), and then setting a value for that DP in XAML markup,
results in the error Failed to create a 'Windows.Foundation.Single'
from the text ''.
So I suggest you to use double dependency property instead of float.
When programming in Swift, what are the advantages and disadvantages for using a struct to hold all your Constants?
Normally, I would go for a class, but swift classes don't support stored type properties yet. I'd like to write my code in the form of Sample A rather in Sample B, purely because of readability, less lines of code and the single statement does what is read (a readable constant that can't be over-written).
// Sample A.swift
struct Constant {
static let PI = 3.14
}
//Sample B.swift
private let globalPI = 3.14
class Constant {
class var PI: Float {
return globalPI
}
}
If I am just referencing Constant.PI from a Struct perspective (for use in computations, printing, conditionals or whatever), am I being wasteful with the copies that are being made? Are there copies made, if I am just referencing the constant as Constant.PI in other parts of my code?
You can declare a class constant in Swift:
class Foo {
class var PI : Double { return 3.1416 }
}
The key is to define the custom getter and no setter.
Here are two classes that I need to map, on the left side:
class HumanSrc {
public int IQ;
public AnimalSrc Animal;
}
class AnimalSrc {
public int Weight;
}
on the right side are the same objects, but composed using inheritance:
class HumanDst : AnimalDst {
public int IQ;
}
class AnimalDst {
public int Weight;
}
so the mapping I need is:
humanSrc.IQ -> humanDst.IQ
humanSrc.Animal.Weight -> humanDst.Weight;
I can easily do this mapping explicitly, but I have several classes that all derive from Animal, and Animal class is large, so I would prefer to map Animal once, and then have that included in every derived class mapping.
I looked at .Include<> method, but I do not think it supports this scenario.
Here is the essence of what I am looking for (pseudo-code):
// define animal mapping
var animalMap = Mapper.CreateMap<AnimalSrc, AnimalDst>().ForMember(dst=>dst.Weight, opt=>opt.MapFrom(src=>src.Weight);
// define human mapping
var humanMap = Mapper.CreateMap<HumanSrc, HumanDst>();
humanMap.ForMember(dst=>dst.IQ, opt=>opt.MapFrom(src=>src.IQ));
// this is what I want. Basically I want to say:
// "in addition to that, map this child property on the dst object as well"
humanMap.ForMember(dst=>dst, opt=>opt.MapFrom(src=>src.Entity));
As a workaround you can add BeforeMap with mapping base class. Probably it is not the best solution but at least it requires less mapping configuration:
humanMap.BeforeMap((src, dst) =>
{
Mapper.Map(src.Animal, (AnimalDst)dst);
});
I am using a third-part .NET library that has the following classes.
Shape (the abstract base class)
(all the below classes derived from him)
Rectangle
Circle
Triangle
all of these classes has a property called Area
I am going through an array of Shape(s), and set the area
P.S: Area is not a property of the Shape, instead it is a property of each class.
so my code looks like this:
if (shapeVar is Reactangle)
{
(shapeVar as Rectangle).area = value;
}
if (shapeVar is Circle)
{
(shapeVar as Circle).area = value;
}
if (shapeVar is Triangle)
{
(shapeVar as Triangle).area = value;
}
Is there a better way to do this?
I feel like it is stupid, but I didn't find other way to do it
I am using .NET 4
You can use reflection to access the area property of each shape, although there is a small performance cost:
shapeVar.GetType().GetProperty("area").SetValue(shapeVar, value, null);
you can wrap Rectangle, Circle and Triangle classes (that come from the third party assembly) and create 3 new classes in your own code.
Then you can have an interface for e.g:
public interface IShape
{
double Area{get;set;}
}
Make the wrapped classes to implement this common interface.
After that you can use all three of these classes in your code in a common way without having to know what their actual concrete classes are. (by referring to Interface type rather than Shape base type)
Why not have the Area be a method that returns from the derived type instead of being set?
public abstract class Shape
{
abstract public double Area();
}
public class Square : Shape
{
double sideLength;
public double Area
{
return sideLength * sideLength;
}
}
public class Circle : Shape
{
double radius;
public double Area
{
return Pi * r * r;
}
}
If you want to stick to setting the area, you could move your Area into the base class :
public abstract class Shape
{
public double Area;
}
public class Square : Shape
{
...
}
and you look through shapes setting the area based on the derived type you could do :
foreach (Shape shape in shapes)
switch(typeof(shape))
{
case typeof(Square))
{
shape.Area = value; //I imagine this is derived type specific
...
}
}
I have a ref class that contains a pointer to an unmanaged class. the class has some basic types and also a vector of objects of another class. I would like to know the best way to get and set the vector from managed code. Will a memcpy between unmangedb objects be efficient or setting each member variable of unmanagedb?
for ex (assume the class is complete. I am writing what is relevant to the question)
Assume we already have a managed wrapped for struct UnmanagedB called B.
struct UnmanagedA
{
int a;
vector<UnmanagedB> list;
};
public ref class A : public System::IDisposable
{
public:
// properties
property System::UInt32 a
{
System::UInt32 get();
void set(System::UInt32 value);
}
property array<B^>^ list
{
System::array<B^>^ get(); // what is the best way to set and get the vector
void set(array<B^>^ value);
}
private:
UnmanagedA* obj1;
};
This obviously won't be cleanly possible, since UnmanagedA contains a vector of UnmanagedB values, while A exposes an property of type array<B^>. If this is intended and not a typo, you will need to marshall the content of B^ into instances of UnmanagedB. Otherwise, let UnmanagedA hold a std::vector< B* > and take care of proper lifetime management.