C++ compiler optimization for linear pointer comparisons - c++

I'm having the following code example (fairly representative of actual code), and I'm trying to make the compiler not emit comparisons for the inline index checks in getVal (line 32).
#include <stdio.h>
#include <stdint.h>
using TValue = uint32_t;
struct CI {
TValue* func;
};
struct LS {
TValue* top;
CI* ci;
};
LS* makeState() {
auto s = new LS();
s->ci = new CI();
s->ci->func = new TValue[4];
s->top = &s->ci->func[3];
return s;
}
inline int assertTop(LS* s, int idx) {
const TValue* o = s->ci->func + idx;
return ((uintptr_t)o <= (uintptr_t)s->top) ? 1 : 0;
}
inline uint32_t getVal(LS* s, int idx) {
const TValue* o = s->ci->func + idx;
if (o >= s->top) {
return -1;
}
return *o;
}
void check(LS* s) {
if (assertTop(s, 3)) {
printf("%d %d %d", getVal(s, 0), getVal(s, 1), getVal(s, 2));
}
}
int main()
{
auto s = makeState();
check(s);
return 0;
}
Practically, since this code can't be reached if the comparison in assertTop fails, and no other code with side effects is executed in between, these additional checks (emitted in check's usage of getVal as can be seen on the godbolt output) should not be needed.
I understand that pointer comparison is a 'weird' scenario that compilers usually will take the 'safe' route for and not optimize, but is there any other way to have the compiler not emit these checks, without actually removing the check from getVal?

Related

Pass a function of object of any type to another object in C++

I'm creating a node system (similar to eg. UE4 or Blender's Cycles) in which i can create nodes of different types and use them later. At the moment I have 2 classes of nodes with output functions like these:
class InputInt
{
public:
int output()
{
int x;
std::cin>>x;
return x;
}
};
class RandomInt
{
public:
int rand10()
{
int x;
x = rand()%10;
return x;
}
int rand100()
{
int x;
x = rand()%100;
return x;
}
};
I don't pass anything to these nodes. Now I want to create a node which takes and output function from and object of one of above classes. Here is how I implemented it to use InputInt node only:
class MultiplyBy2
{
typedef int (InputInt::*func)();
func input_func;
InputInt *obj;
public:
MultiplyBy2(InputInt *object, func i): obj(object), input_func(i) {}
int output()
{
return (obj->*input_func)()*2;
}
};
Having this I can create and use object of MultiplyBy2 in main() and it works perfectly.
int main()
{
InputInt input;
MultiplyBy2 multi(&input, input.output);
std::cout<<multi.output()<<std::endl;
}
It doesn't obviously work for object of RandomInt as I have to pass *InputInt object to MultiplyBy2 object. Is there a way to make MultiplyBy2 take any kind of an object with its output function eg. like this?
int main()
{
RandomInt random;
MultiplyBy2 multi2(&random, random.rand10);
std::cout<<multi2.output()<<std::endl;
}
An alternative approach, using a common base class with virtual methods:
#include <iostream>
struct IntOp {
virtual int get() = 0;
};
struct ConstInt: IntOp {
int n;
explicit ConstInt(int n): n(n) { }
virtual int get() override { return n; }
};
struct MultiplyIntInt: IntOp {
IntOp *pArg1, *pArg2;
MultiplyIntInt(IntOp *pArg1, IntOp *pArg2): pArg1(pArg1), pArg2(pArg2) { }
virtual int get() override { return pArg1->get() * pArg2->get(); }
};
int main()
{
ConstInt i3(3), i4(4);
MultiplyIntInt i3muli4(&i3, &i4);
std::cout << i3.get() << " * " << i4.get() << " = " << i3muli4.get() << '\n';
return 0;
}
Output:
3 * 4 = 12
Live Demo on coliru
As I mentioned std::function in post-answer conversation with OP, I fiddled a bit with this idea and got this:
#include <iostream>
#include <functional>
struct MultiplyIntInt {
std::function<int()> op1, op2;
MultiplyIntInt(std::function<int()> op1, std::function<int()> op2): op1(op1), op2(op2) { }
int get() { return op1() * op2(); }
};
int main()
{
auto const3 = []() -> int { return 3; };
auto const4 = []() -> int { return 4; };
auto rand100 = []() -> int { return rand() % 100; };
MultiplyIntInt i3muli4(const3, const4);
MultiplyIntInt i3muli4mulRnd(
[&]() -> int { return i3muli4.get(); }, rand100);
for (int i = 1; i <= 10; ++i) {
std::cout << i << ".: 3 * 4 * rand() = "
<< i3muli4mulRnd.get() << '\n';
}
return 0;
}
Output:
1.: 3 * 4 * rand() = 996
2.: 3 * 4 * rand() = 1032
3.: 3 * 4 * rand() = 924
4.: 3 * 4 * rand() = 180
5.: 3 * 4 * rand() = 1116
6.: 3 * 4 * rand() = 420
7.: 3 * 4 * rand() = 1032
8.: 3 * 4 * rand() = 1104
9.: 3 * 4 * rand() = 588
10.: 3 * 4 * rand() = 252
Live Demo on coliru
With std::function<>, class methods, free-standing functions, and even lambdas can be used in combination. So, there is no base class anymore needed for nodes. Actually, even nodes are not anymore needed (explicitly) (if a free-standing function or lambda is not counted as "node").
I must admit that graphical dataflow programming was subject of my final work in University (though this is a long time ago). I remembered that I distinguished
demand-driven execution vs.
data-driven execution.
Both examples above are demand-driven execution. (The result is requested and "pulls" the arguments.)
So, my last sample is dedicated to show a simplified data-driven execution (in principle):
#include <iostream>
#include <vector>
#include <functional>
struct ConstInt {
int n;
std::vector<std::function<void(int)>> out;
ConstInt(int n): n(n) { eval(); }
void link(std::function<void(int)> in)
{
out.push_back(in); eval();
}
void eval()
{
for (std::function<void(int)> &f : out) f(n);
}
};
struct MultiplyIntInt {
int n1, n2; bool received1, received2;
std::vector<std::function<void(int)>> out;
void set1(int n) { n1 = n; received1 = true; eval(); }
void set2(int n) { n2 = n; received2 = true; eval(); }
void link(std::function<void(int)> in)
{
out.push_back(in); eval();
}
void eval()
{
if (received1 && received2) {
int prod = n1 * n2;
for (std::function<void(int)> &f : out) f(prod);
}
}
};
struct Print {
const char *text;
explicit Print(const char *text): text(text) { }
void set(int n)
{
std::cout << text << n << '\n';
}
};
int main()
{
// setup data flow
Print print("Result: ");
MultiplyIntInt mul;
ConstInt const3(3), const4(4);
// link nodes
const3.link([&mul](int n) { mul.set1(n); });
const4.link([&mul](int n) { mul.set2(n); });
mul.link([&print](int n) { print.set(n); });
// done
return 0;
}
With the dataflow graph image (provided by koman900 – the OP) in mind, the out vectors represent outputs of nodes, where the methods set()/set1()/set2() represent inputs.
Output:
Result: 12
Live Demo on coliru
After connection of graph, the source nodes (const3 and const4) may push new results to their output which may or may not cause following operations to recompute.
For a graphical presentation, the operator classes should provide additionally some kind of infrastructure (e.g. to retrieve a name/type and the available inputs and outputs, and, may be, signals for notification about state changes).
Surely, it is possible to combine both approaches (data-driven and demand-driven execution). (A node in the middle may change its state and requests new input to push new output afterwards.)
You can use templates.
template <typename UnderlyingClass>
class MultiplyBy2
{
typedef int (UnderlyingClass::*func)();
func input_func;
UnderlyingClass *obj;
public:
MultiplyBy2(UnderlyingClass *object, func i) : obj(object), input_func(i) {}
int output()
{
return (obj->*input_func)() * 2;
}
};
int main()
{
// test
InputInt ii;
MultiplyBy2<InputInt> mii{ &ii, &InputInt::output };
RandomInt ri;
MultiplyBy2<RandomInt> mri{ &ri, &RandomInt::rand10 };
}
This is a bit convoluted. However I think you should be making an interface or class that returns a value and the objects should inherit from this. Then the operator class can take any class that inherits from the base/interface. Eg Make an BaseInt class that stores an int and has the output method/ RandomInt and InputInt should inherit from BaseInt

Cuda C++ design: reusable class with unknown compile-time size

I am looking for a convenient design in order to be able to use a class on the device which has unknown compile-time size.
Only one instance of this class needs to be sent to the device, for which there should be a single call to cudaMalloc and cudaMemcpy (ideally).
The host version of the class would look like this:
Class A {
public:
A(int size) : table(size) {
// some useful initialization of table
}
double get(int i) const {
// return some processed element from table
}
private:
std::vector<int> table;
};
The kernel:
__global__ void kernel(const A *a){
int idx = threadIdx.x + blockDim.x * blockIdx.x;
a->get(idx); // do something useful with it
}
So far, the way I would design the device version of the class is like that:
const int sizeMax = 1000;
Class A {
public:
A(int size) {
// size checking + some useful initialization of table
}
__host__ __device__
double get(int i) const {
//
}
private:
int table[sizeMax];
};
And the client code:
A a(128);
A* da;
cudaMalloc((void**)&da, sizeof(A));
cudaMemcpy(da, &a, sizeof(A), cudaMemcpyHostToDevice);
kernel<<<1, 32>>>(da);
cudaDeviceSynchronize();
cudaFree(da);
This is rather ugly because:
it wastes bandwith by having to use too large a sizeMax in order to
be on the safe side
the class is not closed for modification, the value of sizeMax will
inevitably need to be raised at some point
Is there any other way to achieve the same thing in a cleaner way without negative performance impact? To be clear, I only need the device version of the class, the first version is just the equivalent non-CUDA code to illustrate the fact that the table size should be dynamic.
In my comment, I said:
separate host and device storage for table, contained in the class, both of which are allocated dynamically. 2. dynamic allocation of table storage size in the constructor, rather than in your client code. This could also include resizing if necessary. 3. differentiation in class methods to use either the host copy of the data or the device copy (i.e. pointer) to the data, depending on whether the method is being executed in host or device code 4. A method to copy data from host to device or vice versa, as the class context is moved from host to device or vice versa.
Here's an example of what I had in mind:
#include <stdio.h>
#include <assert.h>
#include <cuda_runtime_api.h>
#include <iostream>
template <typename T>
class gpuvec{
private:
T *h_vec = NULL;
T *d_vec = NULL;
size_t vsize = 0;
bool iscopy;
public:
__host__ __device__
T * data(){
#ifndef __CUDA_ARCH__
return h_vec;
#else
return d_vec;
#endif
}
__host__ __device__
T& operator[](size_t i) {
assert(i < vsize);
return data()[i];}
void to_device(){
assert(cudaMemcpy(d_vec, h_vec, vsize*sizeof(T), cudaMemcpyHostToDevice) == cudaSuccess);}
void to_host(){
assert(cudaMemcpy(h_vec, d_vec, vsize*sizeof(T), cudaMemcpyDeviceToHost) == cudaSuccess);}
gpuvec(gpuvec &o){
h_vec = o.h_vec;
d_vec = o.d_vec;
vsize = o.vsize;
iscopy = true;}
void copy(gpuvec &o){
free();
iscopy = false;
vsize = o.vsize;
h_vec = (T *)malloc(vsize*sizeof(T));
assert(h_vec != NULL);
assert(cudaMalloc(&d_vec, vsize*sizeof(T)) == cudaSuccess);
memcpy(h_vec, o.h_vec, vsize*sizeof(T));
assert(cudaMemcpy(d_vec, o.d_vec, vsize*sizeof(T), cudaMemcpyDeviceToDevice) == cudaSuccess);}
gpuvec(size_t ds) {
assert(ds > 0);
iscopy = false;
vsize = ds;
h_vec = (T *)malloc(vsize*sizeof(T));
assert(h_vec != NULL);
assert(cudaMalloc(&d_vec, vsize*sizeof(T)) == cudaSuccess);}
gpuvec(){
iscopy = false;
}
~gpuvec(){
if (!iscopy) free();}
void free(){
if (d_vec != NULL) cudaFree(d_vec);
d_vec = NULL;
if (h_vec != NULL) ::free(h_vec);
h_vec = NULL;}
__host__ __device__
size_t size() {
return vsize;}
};
template <typename T>
__global__ void test(gpuvec<T> d){
for (int i = 0; i < d.size(); i++){
d[i] += 1;
}
}
int main(){
size_t ds = 10;
gpuvec<int> A(ds);
A.to_device();
test<<<1,1>>>(A);
A.to_host();
for (size_t i = 0; i < ds; i++)
std::cout << A[i];
std::cout << std::endl;
gpuvec<int> B;
B.copy(A);
A.free();
B.to_device();
test<<<1,1>>>(B);
B.to_host();
for (size_t i = 0; i < ds; i++)
std::cout << B[i];
std::cout << std::endl;
B.free();
}
I'm sure quite a few criticisms could be made. This may not adhere to any particular opinion of what "vector syntax" should be. Furthermore I'm sure there are use cases it does not cover, and it may contain outright defects. To create a robust host/device vector realization may require as much work and complexity as thrust host and device vectors. I'm not suggesting that thrust vectors are a drop-in answer for what the question seems to be asking, however.
Based on Robert Crovella's answer, here is a simplified (device only, so ignoring points 3 & 4) working solution:
Class A {
public:
A(int size) : table(size) {
// some useful initialization of table
cudaMalloc((void**)&dTable, sizeof(int) * size);
cudaMemcpy(dTable, &table[0], sizeof(int) * size, cudaMemcpyHostToDevice);
}
~A() {
cudaFree(dTable);
}
__device__
double get(int i) const {
// return some processed element of dTable
}
private:
std::vector<int> table;
int *dTable;
};
Kernel and client code stay exactly the same.

function pointer for different functions with different data types or parameter

i have this code which uses a function pointer to point 3 functions sum, subtract, mul. it works well. but now the problem is that i have functions with different no.of parameters and different data types. how to implement this.
int add(int a, int b)
{
cout<<a+b;
}
int subtract(int a, int b)
{
cout<<a-b;
}
int mul(int a, int b)
{
cout<<a*b;
}
int main()
{
int (*fun_ptr_arr[])(int, int) = {add, subtract, mul};
unsigned int ch, a = 15, b = 10,c=9;
ch=2;
if (ch > 4) return 0;
(*fun_ptr_arr[ch])(a, b);
return 0;
}
The simple answer is that technically you can't do this. You could do some manipulations using an array as input for all these functions, but you will still have to know exactly what to pass to each function. From a software engineering perspective, you should not do this - I suggest you take a look at the nice answers here: C++ Function pointers with unknown number of arguments
A slightly different approach using objects to implement the required behavior. In order to have a truly generic kind of solution, we need to use Interfaces.
Dismantle the data and operation i.e keep them separately.
//Interface which describes any kind of data.
struct IData
{
virtual ~IData()
{
}
};
//Interface which desribes any kind of operation
struct IOperation
{
//actual operation which will be performed
virtual IData* Execute(IData *_pData) = 0;
virtual ~IOperation()
{
}
};
Now, every operation knows the kind of data it work on and will expect that kind of data only.
struct Operation_Add : public IOperation
{
//data for operation addition.
struct Data : public IData
{
int a;
int b;
int result;
};
IData* Execute(IData *_pData)
{
//expected data is "Operation_Add::Data_Add"
Operation_Add::Data *pData = dynamic_cast<Operation_Add::Data*>(_pData);
if(pData == NULL)
{
return NULL;
}
pData->result = pData->a + pData->b;
return pData;
}
};
struct Operation_Avg : public IOperation
{
//data for operation average of numbers.
struct Data : public IData
{
int a[5];
int total_numbers;
float result;
};
IData* Execute(IData *_pData)
{
//expected data is "Operation_Avg::Data_Avg"
Operation_Avg::Data *pData = dynamic_cast<Operation_Avg::Data*>(_pData);
if(pData == NULL)
{
return NULL;
}
pData->result = 0.0f;
for(int i = 0; i < pData->total_numbers; ++i)
{
pData->result += pData->a[i];
}
pData->result /= pData->total_numbers;
return pData;
}
};
Here, is the operation processor, the CPU.
struct CPU
{
enum OPERATION
{
ADDITION = 0,
AVERAGE
};
Operation_Add m_stAdditionOperation;
Operation_Avg m_stAverageOperation;
map<CPU::OPERATION, IOperation*> Operation;
CPU()
{
Operation[CPU::ADDITION] = &m_stAdditionOperation;
Operation[CPU::AVERAGE] = &m_stAverageOperation;
}
};
Sample:
CPU g_oCPU;
Operation_Add::Data stAdditionData;
stAdditionData.a = 10;
stAdditionData.b = 20;
Operation_Avg::Data stAverageData;
stAverageData.total_numbers = 5;
for(int i = 0; i < stAverageData.total_numbers; ++i)
{
stAverageData.a[i] = i*10;
}
Operation_Add::Data *pResultAdd = dynamic_cast<Operation_Add::Data*>(g_oCPU.Operation[CPU::ADDITION]->Execute(&stAdditionData));
if(pResultAdd != NULL)
{
printf("add = %d\n", pResultAdd->result);
}
Operation_Avg::Data *pResultAvg = dynamic_cast<Operation_Avg::Data*>(g_oCPU.Operation[CPU::AVERAGE]->Execute(&stAverageData));
if(pResultAvg != NULL)
{
printf("avg = %f\n", pResultAvg->result);
}
If you have the following functions
int f1(int i);
int f2(int i, int j);
You can define a generic function type like this
typedef int (*generic_fp)(void);
And then initialize your function array
generic_fp func_arr[2] = {
(generic_fp) f1,
(generic_fp) f2
};
But you will have to cast the functions back
int result_f1 = ((f1) func_arr[0]) (2);
int result_f2 = ((f2) func_arr[1]) (1, 2);
Obviously, it does not look like a good way to build a program
To make code look a little bit better you can define macros
#define F1(f, p1) ((f1)(f))(p1)
#define F2(f, p1, p2) ((f2)(f))(p1, p2)
int result_f1 = F1(func_arr[0], 2);
int result_f2 = F2(func_arr[1], 1, 2);
EDIT
Forgot to mention, you also have to define a type for every type of function
typedef int (*fi)(int); // type for function of one int param
typedef int (*fii)(int, int); // type for function of two int params
And to then cast stored pointers to those types
int result_f1 = ((fi) func_arr[0]) (2);
int result_f2 = ((fii) func_arr[1]) (1, 2);
Here is a complete example
#include <iostream>
typedef int (*generic_fp)(void);
typedef int (*fi)(int); // type for function of one int param
typedef int (*fii)(int, int); // type for function of two int params
#define F1(f, p1) ((fi)(f))(p1)
#define F2(f, p1, p2) ((fii)(f))(p1, p2)
int f1(int i);
int f2(int i, int j);
int main()
{
generic_fp func_arr[2] = {
(generic_fp) f1,
(generic_fp) f2
};
int result_f1_no_macro = ((fi) func_arr[0]) (2);
int result_f2_no_macro = ((fii) func_arr[1]) (1, 2);
int result_f1_macro = F1(func_arr[0], 2);
int result_f2_macro = F2(func_arr[1], 1, 2);
std::cout << result_f1_no_macro << ", " << result_f2_no_macro << std::endl;
std::cout << result_f1_macro << ", " << result_f2_macro << std::endl;
return 0;
}
int f1(int i)
{
return i * 2;
}
int f2(int i, int j)
{
return i + j;
}
The code above produces the following output
4, 3
4, 3

C++ Use Function Preconditions Or Wrapper Classes with Invariants?

I find myself writing a lot of functions that begin with many preconditions, and then I have to figure out how to handle all the invalid inputs and write tests for them.
Note that the codebase I work in does not allow throwing exceptions, in case that becomes relevant in this question.
I am wondering if there is any C++ design pattern where instead of having preconditions, input arguments are passed via wrapper classes that guarantee invariants. For example suppose I want a function to return the max value in a vector of ints. Normally I would do something like this:
// Return value indicates failure.
int MaxValue(const std::vector<int>& vec, int* max_value) {
if (vec.empty()) {
return EXIT_FAILURE;
}
*max_value = vec[0];
for (int element : vec) {
if (element > *max_value) {
*max_value = element;
}
}
return EXIT_SUCCESS;
}
But I am wondering if there is a design pattern to do something like this:
template <class T>
class NonEmptyVectorWrapper {
public:
static std::unique_ptr<NonEmptyVectorWrapper>
Create(const std::vector<T>& non_empty_vector) {
if (non_empty_vector.empty()) {
return std::unique_ptr<NonEmptyVectorWrapper>(nullptr);
}
return std::unique_ptr<NonEmptyVectorWrapper>(
new NonEmptyVectorWrapper(non_empty_vector));
}
const std::vector<T>& vector() const {
return non_empty_vector_;
}
private:
// Could implement move constructor/factory for efficiency.
NonEmptyVectorWrapper(const std::vector<T>& non_empty_vector)
: non_empty_vector_(non_empty_vector) {}
const std::vector<T> non_empty_vector_;
};
int MaxValue(const NonEmptyVectorWrapper<int>& vec_wrapper) {
const std::vector<int>& non_empty_vec = vec_wrapper.vector();
int max_value = non_empty_vec[0];
for (int element : non_empty_vec) {
if (element > max_value) {
max_value = element;
}
}
return max_value;
}
The main pro here is that you avoid unnecessary error handling in the function. A more complicated example where this could be useful:
// Finds the value in maybe_empty_vec which is closest to integer n.
// Return value indicates failure.
int GetValueClosestToInt(
const std::vector<int>& maybe_empty_vec,
int n,
int* closest_val);
std::vector<int> vector = GetRandomNonEmptyVector();
for (int i = 0; i < 10000; i++) {
int closest_val;
int success = GetValueClosestToInt(vector, i, &closest_val);
if (success) {
std::cout << closest_val;
} else {
// This never happens but we should handle it.
}
}
which wastefully checks that the vector is non-empty each time and checks for failure, versus
// Returns the value in the wrapped vector closest to n.
int GetValueClosestToInt(
const NonEmptyVectorWrapper& non_empty_vector_wrapper,
int n);
std::unique_ptr<NonEmptyVectorWrapper> non_empty_vector_wrapper =
NonEmptyVectorWrapper::Create(GetRandomNonEmptyVector());
for (int i = 0; i < 10000; i++) {
std::cout << GetValueClosestToInt(*non_empty_vector_wrapper, i);
}
which can't fail and gets rid of the needless input checking.
Is this design pattern a good idea, is there a better way to do it, and is there a name for it?

c++ Object is creating two instances of the same array, but in different scopes?

Im having an issue with one of my classes. The class has only 1 array<> member in it. I am building a static object of this class, and initializing the values in a function. The problem is the values are never inserted.
When I step into the debugger and look at some basic insert statements into this array, the array remains empty. However if I step into the insert function itself, I can see a 'second' array of the exact same name, storing the values as expected.
It looks to me as though there is the static outer scoped array, which has nothing in it, and a second internal version (the exact same array) that has the contents stored properly.
Is there something I am missing here? I really dont know why this is happening.
Here is the minimum source code, as per request
circularbuffer.hpp
#ifndef __ma__circularbuffer_guard
#define __ma__circularbuffer_guard
#include <array>
template < typename T, int SIZE>
class CircularBuffer
{
private:
int _index;
int _size;
std::array<T, SIZE> _buffer;
public:
CircularBuffer() { _index = 0; _size = SIZE; }
int length ();
typename T& at (int);
void insert (T);
int index ();
private:
int realign (int&);
};
template < typename T, int SIZE>
int CircularBuffer<T, SIZE>::realign (int& index)
{
if (index >= _size)
{
index -= _size;
realign(index);
} else if (index < 0)
{
index += _size;
realign(index);
}
return index;
}
template < typename T, int SIZE>
int CircularBuffer<T, SIZE>::length ()
{
return _size;
}
template < typename T, int SIZE>
typename T& CircularBuffer<T, SIZE>::at (int index)
{
realign(index);
return _buffer.at(index);
}
template <typename T, int SIZE>
void CircularBuffer<T, SIZE>::insert (T data)
{
realign(_index);
_buffer.at(_index) = data;
_index += 1;
}
template <typename T, int SIZE>
int CircularBuffer<T, SIZE>::index ()
{
return _index;
}
#endif
global buffer initializer
#ifndef __guard__namespace__notes__
#define __guard__namespace__notes__
#include "circularbuffer.hpp"
#include <memory>
typedef CircularBuffer<char, 7> CB_Natural_T;
typedef CircularBuffer<int, 12> CB_Chromatic_T;
static CB_Natural_T WHITENOTES = CB_Natural_T(); // buffer of letter notes
static CB_Chromatic_T POSITIONS = CB_Chromatic_T(); // buffer of absolute positions on keyboard
struct Initialize
{
Initialize()
{
WHITENOTES.insert('C');
WHITENOTES.insert('D');
WHITENOTES.insert('E');
WHITENOTES.insert('F');
WHITENOTES.insert('G');
WHITENOTES.insert('A');
WHITENOTES.insert('B');
// Initialize all positions
for (int i = 0; i < 12; ++i)
POSITIONS.insert(i);
}
};
static Initialize dummy_init_var = Initialize();
#endif
to initialize the static buffers so I can unit test my other classes.
Note class header and cpp
#ifndef __guard__note__
#define __guard__note__
#include "macros.h"
#include <string>
#include <memory>
class Note
{
public:
enum Qualities { UNKNOWN = -3, DFLAT, FLAT, NATURAL, SHARP, DSHARP }; // qualities of note
typedef DEF_PTR(Note); // pointer type
private:
char _letter [1]; // the letter of the note
std::string _name; // the full name of the note
int _value; // absolute value
int _position; // relative position
Qualities _quality; // sharp/natural/flat quality
public:
Note();
Note(char); // letter
Note(char, Qualities); // letter, and quality
// setters
void sharp(); // Sets the quality of the note to 1
void Dsharp(); // Sets the quality of the note to 2
void flat(); // Sets the quality of the note to -1
void Dflat(); // Sets the quality of the note to -2
void natural(); // Sets the quality of the note to 0
// getters
char letter() const; /* returns character letter */
std::string name() const; /* returns true name of note */
int position() const; /* returns relative position on keyboard */
int quality() const; /* returns the quality of the note */
void respell() const; /* respells a note to the nearest other note */
static pointer_type make(char); // returns a shared pointer of a new Note
static pointer_type make(char, Qualities); // returns a shared pointer of a new Note
// operators
bool operator ==(Note& r) const; // Returns true if Notes are truly equal
bool operator !=(Note& r) const; // Returns true if Notes are truly not equal
bool isEnharmonic(Note& r) const; // Returns true if Notes are enharmonically equal
bool isNatural() const; // Returns true if Note is natural
bool isSharp() const; // Returns true if Note is sharp
bool isDSharp() const; // Returns true if Note is double sharp
bool isFlat() const; // Returns true if Note is flat
bool isDFlat() const; // Returns true if Note is double flat
private:
void makeName(); /* sets name of Note */
};
#endif
#include "note.h"
Note::Note()
{
_letter[1] = 'u';
_name = "";
_value = -1;
_quality = UNKNOWN;
_position = -1;
}
Note::Note(char l)
{
_letter[1] = l;
// determine absolute value based on letter
switch (l)
{
case 'C':
_value = 0; break;
case 'D':
_value = 2; break;
case 'E':
_value = 4; break;
case 'F':
_value = 5; break;
case 'G':
_value = 7; break;
case 'A':
_value = 9; break;
case 'B':
_value = 11; break;
default:
_value = -1; break;
}
_quality = NATURAL;
_position = _value + _quality;
makeName();
}
Note::Note(char l, Note::Qualities q)
{
_letter[1] = l;
// determine absolute value based on letter given
switch (l)
{
case 'C':
_value = 0; break;
case 'D':
_value = 2; break;
case 'E':
_value = 4; break;
case 'F':
_value = 5; break;
case 'G':
_value = 7; break;
case 'A':
_value = 9; break;
case 'B':
_value = 11; break;
default:
_value = -1; break;
}
_quality = q; // assert for good data
_position = _value + _quality;
makeName();
}
void Note::sharp() { _quality = SHARP; _position = _value + 1; makeName();}
void Note::Dsharp() { _quality = DSHARP; _position = _value + 2; makeName();}
void Note::flat() { _quality = FLAT; _position = _value - 1; makeName();}
void Note::Dflat() { _quality = DFLAT; _position = _value - 2; makeName();}
void Note::natural() { _quality = NATURAL; _position = _value; makeName(); }
char Note::letter() const { return _letter[1]; }
std::string Note::name() const { return _name; }
int Note::position() const { return _position; }
int Note::quality () const { return _quality; }
Note::pointer_type Note::make(char l) { return pointer_type(new Note(l)); }
Note::pointer_type Note::make(char l, Note::Qualities q) { return pointer_type(new Note(l, q)); }
void Note::makeName()
{
_name = "";
_name += _letter[1]; // add letter to name
// find out quality, add quality to name
switch (_quality)
{
case DFLAT:
_name += "bb"; break;
case FLAT:
_name += "b"; break;
case SHARP:
_name += "#"; break;
case DSHARP:
_name += "x"; break;
case NATURAL:
break;
default:
_name += "u"; break;
}
}
bool Note::operator ==(Note& r) const
{
// true if letter, value, position, and quality are all equal
return (_letter[1] == r._letter[1]) && (_value == r._value) && (_position == r._position) && (_quality == r._quality);
}
bool Note::operator !=(Note& r) const
{
return !(*this == r);
}
bool Note::isEnharmonic (Note& r) const
{
return (_position == r._position);
}
bool Note::isNatural() const
{
return _quality == NATURAL;
}
bool Note::isSharp() const
{
return _quality == SHARP;
}
bool Note::isDSharp() const
{
return _quality == DSHARP;
}
bool Note::isFlat() const
{
return _quality == FLAT;
}
bool Note::isDFlat() const
{
return _quality == DFLAT;
}
I would post interval as well, but that one is very big. But basically There is this code inside one of Intervals functions called findInterval
Interval::findInterval
void Interval::findInterval(Note& bottom, Note& top)
{
int index = 0; // temp placeholder for start position
// find where the bottom note is in relation to buffer
for (int i = 0; i < WHITENOTES.length(); ++i)
{
if (bottom.letter() == WHITENOTES.at(i))
{
index = i; // set start position to this position
break;
}
}
// find the interpreted interval
// starting from index, with offset of length + index
for (int i = index; i < (index + WHITENOTES.length()); ++i)
{
if (top.letter() == WHITENOTES.at(i))
{
_interval = i - index; // set interval
break;
}
}
// modify index to serve as the position of the bottom note
index = bottom.position();
// find the physical distance
for (int i = index; i < (index + POSITIONS.length()); ++i)
{
if (top.position() == POSITIONS.at(i)) // values match
{
_distance = i - index; // set physical distance
break;
}
else if (top.position() > 11 && ((top.position() - 11) == POSITIONS.at(i))) // if top position is higher than octave
{
_distance = (i - index) + 11;
break;
}
}
}
It fails to set the data members here, because WHITENOTES is empty, even though i called to initialize it with a static struct.
One other thing to note, if I compile my ut_interval, the tests all come back perfect with no failures, and when i check the values of the buffers in the debugger, they show up as being \0. however it still goes through the if statements and matches the char with the letter (is this some sort of encryption on chars in the debugger?)
However, exact same #includes in ut_chord, and it fails to evaluate the intervals
Here is a sample of the interval ut, and chord ut
ut_interval
#include "../common/namespace_notes.h"
#include "../common/note.h"
#include "../common/interval.h"
#define BOOST_TEST_MODULE IntervalTest
#include <boost/test/auto_unit_test.hpp>
#define TEST_IVL(i, dist, itv, q, n) \
BOOST_CHECK(i.distance() == dist); \
BOOST_CHECK(i.interval() == i.itv); \
BOOST_CHECK(i.quality() == i.q); \
BOOST_CHECK(i.name() == n)
BOOST_AUTO_TEST_CASE(INTERVAL_UNISONS)
{
// make some notes
Note C = Note('C');
Note Cs = Note('C', Cs.SHARP);
Note Cds = Note('C', Cds.DSHARP);
Note Cf = Note('C', Cf.FLAT);
Note Cdf = Note('C', Cdf.DFLAT);
// make some intervals
Interval PUnison = Interval(C, C);
Interval AugUnison = Interval(C, Cs);
Interval Aug2Unison = Interval(C, Cds);
Interval DimUnison = Interval(C, Cf);
Interval Dim2Unison = Interval(C, Cdf);
// make sure members are accurate
TEST_IVL(PUnison, 0, UNISON, PER, "Perfect Unison");
BOOST_CHECK(PUnison.isPerfect());
TEST_IVL(AugUnison, 1, UNISON, AUG, "Augmented Unison");
BOOST_CHECK(AugUnison.isAugmented());
TEST_IVL(Aug2Unison, 2, UNISON, AUG, "Augmented Unison");
BOOST_CHECK(AugUnison.isAugmented());
TEST_IVL(DimUnison, 1, UNISON, AUG, "Augmented Unison");
BOOST_CHECK(DimUnison.isAugmented());
TEST_IVL(Dim2Unison, 2, UNISON, AUG, "Augmented Unison");
BOOST_CHECK(Dim2Unison.isAugmented());
}
ut_chord
#include "../common/namespace_notes.h"
#include "../common/note.h"
#include "../common/interval.h"
#include "../common/chord.h"
#define BOOST_TEST_MODULE ChordTest
#include <boost/test/auto_unit_test.hpp>
#include <memory>
BOOST_AUTO_TEST_CASE(ChordConstructor)
{
typedef std::shared_ptr<Note> nt;
nt C = nt(new Note('C'));
nt E = nt(new Note('E'));
nt G = nt(new Note('G'));
nt B = nt(new Note('B'));
Interval PUnison = Interval(*C, *C); // cannot determine this interval
Chord C7 = Chord(C , E, G, B);
Chord C72 = Chord(B, G, E, C);
Chord C73 = Chord(E, G, C, B);
}
Firstly, you should not include a .cpp file. To fix the linker problem you are having, follow the inclusion model: place your function definitions in the template's header file.
Secondly, I have tried the following example program and it works now - the problem might have been due to the linker error.
Read this SO question for more information regarding including a cpp file (and templates).
main.cpp:
#include <array>
#include "circularbuffer.h"
typedef CircularBuffer<char, 7> CB_Natural_T;
typedef CircularBuffer<int, 12> CB_Chromatic_T;
static CB_Natural_T WHITENOTES = CB_Natural_T(); // buffer of letter notes
static CB_Chromatic_T POSITIONS = CB_Chromatic_T();
int main()
{
WHITENOTES.insert('C');
WHITENOTES.insert('D');
WHITENOTES.insert('E');
WHITENOTES.insert('F');
WHITENOTES.insert('G');
WHITENOTES.insert('A');
WHITENOTES.insert('B');
// Initialize all positions
for (int i = 0; i < 12; ++i)
POSITIONS.insert(i);
return 0;
}
circularbuffer.h:
#ifndef _CIRCULAR_BUFFER_H
#define _CIRCULAR_BUFFER_H
#include <array>
template < class T, int SIZE>
class CircularBuffer
{
private:
int _index;
int _size;
std::array<T, SIZE> _buffer;
public:
CircularBuffer() : _index(0), _size(SIZE), _buffer() {}
int length ()
{
return _size;
}
T& at (int index)
{
realign(index);
return _buffer.at(index);
}
void insert (T data)
{
realign(_index);
_buffer.at(_index) = data;
_index += 1;
}
int index ()
{
return _index;
}
private:
int realign (int& index)
{
if (index >= _size)
{
index -= _size;
realign(index);
} else if (index < 0)
{
index += _size;
realign(index);
}
return index;
}
};
#endif
Also, use inclusion guards to make sure your files are not included twice.
static CB_Natural_T WHITENOTES = CB_Natural_T();
static CB_Chromatic_T POSITIONS = CB_Chromatic_T();
It is these two that don't behave as you expect them to, right? Since these are globals, you should put
extern CB_Natural_T WHITENOTES;
extern CB_Chromatic_T POSITIONS;
into a header file to declare them and
CB_Natural_T WHITENOTES;
CB_Chromatic_T POSITIONS;
into a cpp file to actually define them. The static caused these objects to have internal linkage, so every file (precisely: compilation unit) that includes the header will have two such objects created instead of sharing them between different files.
I also think these two objects are constants, right? In that case, you could declare them as such. You would then need a helper that generates these objects or a constructor that allows initializing:
CB_Natural_T whitenotes()
{
CB_Natural_T init;
...
return init;
}
CB_Natural_T const WHITENOTES = whitenotes();
Notes:
The "= T()" is redundant, as already mentioned.
The template SIZE parameter is stored in an int, which is unnecessary since the value is always present.
You are using a realign() function that both modifies the argument and returns the result. I'd use one of these only. Also, since it is a function that only modifies a parameter without touching any members (see point above!), you could make it a static function. At least it should be a const member function.