generic programming – Constructor and destructor as global function instead of member function

I was reading this wonderful interview with Alex Stepanov (the father of C++ STL) http://www.stlport.org/resources/StepanovUSA.html. It really worths the time, about the end of it, there is this question (emphasis mine):

Question:
A frequent dilemma for me was: should I design this function as a member function or as a generic (global) function? what has been the rationale of this decision in STL?

Answer:
Make it global if it at all possible. It would be much nicer if begin and end were global – it would allow us to define them for C arrays. It would be so much nicer if operator* was global with the default definitions:

template <class T> T& operator*(T& x) { return x;}

template <class T> const T& operator*(const T& x) { return x;}

It would allow us to write:

copy(0, 25, ostream_iterator<int>("n"));

In general, for non-iterator objects operator* should return the object itself, the “meaning” of a non-naming thing is a thing itself. I would even love to write constructors and destructors as global functions. You could do some amazing stuff if this is allowed in the language.

The sentence in bold sparked my curiosity, I have tried to google it but the result set is full of intro C++ material if I am not specific enough and just the link to the interview if I am too specific.

Do you have any examples of “amazing stuff”? Is there any language that allowed it?

The interview is quite old, I was wondering if this specific topic has been explored more. If you point me in the right direction will be great.

C# List of generic class that implements a type-specific function

I’m having trouble getting my head around how to even ask this question, so any help would be much appreciated

This is essentially what I want to do:

List<IMagicType> values1 = new List<IMagicType>();
List<IMagicType> values2 = someAlreadyExistingListOfMagicType;

Vector3 position = someVector3;
Quaternion rotation = someQuat;
bool sleeping = false;

values1.MagicAdd(position); //or maybe something like values1.Add(new IMagicType<Vector3>()) or whatever
values1.MagicAdd(rotation);
values1.MagicAdd(sleeping);

List<byte> result = new List<byte>();

foreach(IMagicType value1 in values1)
{
    foreach(IMagicType value2 in values2)
    {
        if(value1.Compare(Value2))
        {
            result.AddRange(value1.GetBytes());
        }
    }
}

So I need a way for IMagicType to understand what the type is in order to properly implement the compare function, and to be able to intelligently convert the value to a byte array.

I’m sure there must be a straightforward solution here but I’ve spent so long on this I can’t think straight any more. How can I solve my problem?

Generic Queue in C – Code Review Stack Exchange

I’m implementing a generic (ie. void *) queue in C. I believe I have a working version but I’m looking for two things:

  • Do any subtle bugs pop out to the experienced reader?
  • Can I implement this in a better way (perhaps using void ** pointers?

queue.h

#ifndef QUEUE_H
#define QUEUE_H

#include <stdbool.h>
#include <stdlib.h>

typedef struct Queue Queue;

void   queue_free     (Queue* queue);
Queue* queue_init     (void);

void*  queue_dequeue  (Queue* queue);
void   queue_enqueue  (Queue* queue, void* item);

bool   queue_is_empty (const Queue* queue);
void   queue_iterate  (const Queue* queue, void (*fn)(void*));
size_t queue_size     (const Queue* queue);

#endif

queue.c

#include "queue.h"

#include <assert.h>
#include <stddef.h>
#include <stdio.h>

struct Queue {
  size_t capacity, size;
  void** data;
  size_t head, tail;
};

void queue_free(Queue* queue) {
  assert(queue);
  
  free(queue->data);
  free(queue);
}

Queue* queue_init(void) {
  Queue* queue = calloc(1, sizeof *queue);
  assert(queue);  
  queue->capacity = 100;
  queue->size = 0;
  queue->data = calloc(queue->capacity, sizeof *queue->data);
  assert(queue->data);
  queue->head = 0;
  queue->tail = 0;
  return queue;
}

void* queue_dequeue(Queue* queue) {
  assert(queue);

  if (queue->size == 0) {
    return NULL;
  }
  void* item = queue->data(queue->head);
  queue->head = (queue->head + 1) % queue->capacity;
  queue->size--;
  assert(item);
  return item;
}

void queue_enqueue(Queue* queue, void* item) {
  assert(queue);
  assert(item);

  if (queue->size == queue->capacity) {
    size_t scale = 2;
    void** tmp = realloc(queue->data, scale * queue->capacity * sizeof *queue->data);
    assert(tmp);
    for (size_t i = queue->head; i < queue->capacity; ++i) {
      tmp(i + queue->capacity) = queue->data(i);
    }
    queue->data = tmp;
    if (queue->head >= queue->tail) {
      queue->head += queue->capacity;
    }
    queue->capacity *= scale;
  }
  queue->data(queue->tail) = item;
  queue->tail = (queue->tail + 1) % queue->capacity;
  queue->size++;
}

bool queue_is_empty(const Queue* queue) {
  assert(queue);
  return queue->size == 0;
}

void queue_iterate(const Queue* queue, void (*fn)(void*)) {
  assert(queue);
  assert(fn);

  if (queue->size == 0) {
    return;
  }
  for (size_t i = 0; i < queue->size; ++i) {
    void* x = queue->data((i + queue->head) % queue->capacity);
    fn(x);
  }
}

size_t queue_size(const Queue* queue) {
  assert(queue);
  
  return queue->size;
}

entity framework – C# Winforms App ,EF6, DB First with Auto Mapper Generic Repository and UOW context is not updated automatically when database is changed externally

I’ve started to work on a single user c# winforms application, with EF6 db first approach, AutoMapper, Generic Repository and UnitOfWork. They have been previously implemented by others former colleagues . I’m not very experienced with those concepts but I have read a lot of links.
The main issue is now that the single user c# app needs to be updated for multiuser environment. Using the current implementation , the external changes(like update operations) performed on database are not visible inside de controller.

I’ve tried using _unitOfWork.Context.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, _tableRepository.FindAllInContext()); to refresh the context but I think this is not a good option, because if I try to update a table column value after refresh, the action will not be saved in database.

 public interface IDbEntity
    {
        int Id { get; set; }
        bool IsDeleted { get; set; }
    }
 
 public interface IRepository<T, T1>
        where T : class, IDbEntity
        where T1 : class, IDbEntity
    {
        int Add(T1 newEntityViewModel);
        void AddRange(List<T1> newEntities);
        void Remove(int id);
        void RemoveFromDb(int id);
        List<T1> Find(Expression<Func<T1, bool>> predicate);
        T1 FindById(int id);
        List<T1> FindAll();
        T FindByIdInContext(int id);
        int GetNextId();
        List<T> FindAllInContext();
    }
    
    internal class DbRepository<T, T1> : IRepository<T, T1>
        where T : class, IDbEntity
        where T1 : class, IDbEntity
    {
        protected ObjectSet<T> _objectSet;
        protected List<T1> _internalList;
        protected ObjectContext _context;

        public DbRepository(ObjectContext context)
        {
            try
            {
                
                _internalList = new List<T1>();
                _objectSet = context.CreateObjectSet<T>();
                _context = context;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }



        public int Add(T1 newEntityViewModel)
        {
            try
            {
                var entityDto = AutoMapperConfiguration.GetMapperConfiguration().Map<T1, T>(newEntityViewModel);
                _objectSet.AddObject(entityDto);

                _context.SaveChanges();
                
                //check id 
                return entityDto.Id;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }


        public List<T1> Find(Expression<Func<T1, bool>> predicate)
        {
            try
            {
                var listT1 = AutoMapperConfiguration.GetMapperConfiguration().Map<List<T1>>(_objectSet.Where(q => !q.IsDeleted));
                var result = listT1.Where(predicate.Compile()).ToList();

                return result;
            }
            catch (Exception ex)
            {
               log.Error(ex.Message);
                throw;
            }
        }

        public List<T1> FindAll()
        {
            try
            {
                var listT1 = AutoMapperConfiguration.GetMapperConfiguration().Map<List<T1>>(_objectSet.Where(q => !q.IsDeleted));
                return listT1;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }

    }
    
    
    public interface IUnitOfWork
    {
        IRepository<User, User_ViewModel> Users { get; }
        IRepository<Type, Type_ViewModel> Types { get; }
        
        /// and a lot more repositories

        ObjectContext Context { get; }
        void Commit();
    }
    
    
    internal class DbUnitOfWork : IUnitOfWork
    {
        private DbRepository<User, User_ViewModel> _users = null;
        private DbRepository<Type, Type_ViewModel> _types = null;
       
       
       
        private readonly ObjectContext _context;
        private readonly EntityConnection _connectionString;

   
        public ObjectContext Context { get { return _context; } }

        public DbUnitOfWork(EntityConnection connectionString)
        {
            try
            {
                _connectionString = connectionString;
                _context = new ObjectContext(connectionString, true);
                _context.ContextOptions.LazyLoadingEnabled = true;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }

        public IRepository<User, User_ViewModel> Users
        {
            get
            {
                return _users ?? (_users = new DbRepository<User, User_ViewModel>(_context));
            }
        }


        public IRepository<Type, Type_ViewModel> Types
        {
            get
            {
                return _types ?? (_types = new DbRepository<Type, Type_ViewModel>(_context));
            }
        }



        public void Commit()
        {
            try
            {
               _context.SaveChanges();

            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw;
            }
        }

    }
    
    DbController.cs
    public partial class DbController
    {
        protected readonly IUnitOfWork _unitOfWork;
        
        protected readonly IRepository<User, User_ViewModel> _userRepository;
        protected readonly IRepository<Type, Type_ViewModel> _typeRepository;
        
        
        public SafeIOController(IUnitOfWork unitOfWork)
        {
           

            _unitOfWork = unitOfWork;
            
            _userRepository = _unitOfWork.Users;
            _typeRepository = _unitOfWork.Types;
            
        }

        public void Save()
        {
            _unitOfWork.Commit();
        }
    }
    Controller_User.cs
    public partial class DbController
    {
       

        public List<User_ViewModel> GetAllUsers()
        {
            try
            {
                
                return _userRepository.FindAll();

            }
            catch (Exception ex)
            {
                _exHandler.LogErrorMessage(Constants_Exception.DB_EXCEPTION_MSG, ex, _exHandler.GetCurrentMethod());
                throw;
            }
        }


        
    }
    
    and then in winforms app 
    
            _unitOfWork = new DbUnitOfWork(connectionString);
            _controller = new DbController(_unitOfWork);

How can I properly implement unitOfWork in order to have the latest information from db inside my context?

c++11 – C++ generic callback implementation

I have a code that takes messages from flash player in a form of XML parse them into function and arguments and calls a registered callback for that function.
The piece of code that I want to replace is something nicely done (almost) generic Callback mechanism:
code for the generic callback implementation of flashSDK (ASInterface.inl).

The problem with it is that this code is written for flash and I want to replace the flash and use other service that will have the same interface. Is there any standard implementation of this callback mechanism (std? boost? something else open sourced?)?

This code implements generic callbacks mechanism that you can register function with number of arguments and types in a map:

void SomethingHappened(int a, int b) {print a + b;}
void SomethingElseHappened(string abcd) {print abcd;}
callbacks("SomethingHappened") = &SomethingHappened;
callbacks("SomethingElseHappened") = &SomethingElseHappened;

and than search for it and call with an array of arguments:

Callbacks::iterator itCallback = callbacks.find(functionName);
if (itCallback != callbacks.end())
{
    HRESULT result = itCallback->second.Call(arguments, returnValue);
}

full usage example:

//init callbacks
typedef std::map<std::wstring, Callback> callbacks;
void SomethingHappened(int a, int b) {print a + b;}
void SomethingElseHappened(string abcd) {print abcd;}
callbacks(functionName) = &SomethingHappened;

void MessageArrived(string xmlInput)
{
    string functionName = parseFunctionName(xmlInput);
    Callbacks::iterator itCallback = callbacks.find(functionName);
    if (itCallback != callbacks.end())
    {
        //parse arguments
        std::vector<std::wstring> args;
        _Args::split(xml, args);
        ASValue::Array arguments;
        for (size_t i = 0, s = args.size(); i < s; ++i)
        {
            ASValue arg; arg.FromXML(args(i));
            arguments.push_back(arg);
        }
        ASValue returnValue;
        //***this is where the magic happens: call the function***
        HRESULT result = itCallback->second.Call(arguments, returnValue);
        return result;
    }
}

backup – I am currently using Ubuntu 20.04.2 LTS with Linux 5.4.0-65 generic and I am having a minor issue with the back ups

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




javascript – Generic CRUDL service

I’m writing a generic CRUDL service as a base for a lot of simple objects that operate similarly on the database. My first though would be to write something like this:

export class CRUDLService<C, R, U, D, L, T> {
  async create(fields: C, connection: Connection): Promise<T> { ... }
  async read(fields: R, connection: Connection): Promise<T> { ... }
  async update(fields: U, connection: Connection): Promise<T> { ... }
  async delete(fields: D, connection: Connection): Promise<T> { ... }
  async list(fields: L, connection: Connection): Promise<T> { ... }
}

But to me it looks heavy on the types.

Are there any alternatives to this approach?

Would this work?

c# – Alternative To Generic Methods where Type is known at runtime

I’ve written a class that synchronizes a table between two databases using Dapper. The public and private Methods in the class are generic and the generic parameter is the POCO class that is being synchronized.

var Sync = new syncClass(localConn, remoteConn);
await Sync.SyncTable<myTablePoco1>();

I feel a little back story will help:

For simplicity sake, I want to wrap all of the synchronization inside a serializable transaction(pushing and pulling), so that if anything goes wrong, I can rollback.

Next, I want to synchronize multiple tables and trying to come up with an appropriate way manage the multiple tables. The consumer could write multiple lines:

await Sync.StartTransaction();
await Sync.SyncTable<myTablePoco1>();
...
...
await Sync.SyncTable<myTablePoco10>();
await Sync.Complete();

I was trying to find a way to encapulate all of the table syncing like so:

Sync.AddTablePoco(typeof(MyTablePoco1));
...
Sync.AddTablePoco(typeof(MyTablePoco1));
...
await Sync.SyncAllTables();
Public async Task SyncAllTables()
{
   foreach (var pocoClass in TableList)
   {
      Sync.SyncTable<pocoClass>(); <-- compiler does not like this
   }
}

I have started to re-write all the generic methods to something with a signature like this:
public async Task SyncTable(Type tableEntity)

At some point down the line of converting I run into this scenario :
private async Task<Ienumerable<?>> FindRecordsToSync(Type tableEntity) <--cannot return a generic type How to handle this

Do I need to use Dynamic types? Is that a code smell? I’m a little stuck and looking for some direction on how to accomplish this.

I’ve looked into reflection as an option to invoke a generic method, but would prefer a non-reflection way.

thread safety – Concurrent, Async Generic Queue C#

I have written this implmentation to assist with a print queue in C#. I have borrowed a substantial amount of code from this answer on SO and modified slightly to include a custom async action.

Be glad of thoughts or how to improve it

Example Usage

    private static ConcurrentAsyncQueue<PrintJob> _printQueue;
    private static ConcurrentAsyncQueue<PrintJob> PrintQueue
    {
        get
        {
            if(_printQueue is null)
            {
                _printQueue = new ConcurrentAsyncQueue<PrintJob>(printJob =>
                {
                    try
                    {
                        // do stuff with printJob Synchronously
                    }
                    catch (Exception ex)
                    {
                        ex.Log();
                    }
                });

                // **** OR ASYNC VERSION ****

                _printQueue = new ConcurrentAsyncQueue<PrintJob>(async printJob =>
                {
                    try
                    {
                        // do stuff with printJob Asyncronously
                    }
                    catch (Exception ex)
                    {
                        await ex.LogAsync();
                    }
                });

            }

            return _printQueue;
        }
    }



public class ConcurrentAsyncQueue<T> : IDisposable where T : class
{
    private readonly ConcurrentQueue<T> _processingQueue = new ConcurrentQueue<T>();
    private Thread _worker;
    private volatile bool _workerTerminateSignal = false;
    private readonly EventWaitHandle _waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

    public bool HasQueuedItem
    {
        get
        {
            lock (_processingQueue)
            {
                return _processingQueue.Any();
            }
        }
    }

    public T NextQueuedItem
    {
        get
        {
            if (!HasQueuedItem)
                return null;

            lock (_processingQueue)
            {
                if (!_processingQueue.TryDequeue(out var result))
                    return null;
                
                return result;
            }
        }
    }

    public void Enqueue(T item)
    {
        lock (_processingQueue)
        {
            _processingQueue.Enqueue(item);
        }
        _waitHandle.Set();
    }

    private readonly Func<T, Task> _processingActionAsync;

    public ConcurrentAsyncQueue(Action<T> processingAction) : this(action =>
    {
        processingAction(action);
        return Task.CompletedTask;
    })
    {

    }

    public ConcurrentAsyncQueue(Func<T, Task> processingActionAsync)
    {
        _processingActionAsync = processingActionAsync ?? throw new Exception("Action cannot be null!");
        _worker = new Thread(async () => await ProcessQueueAsync());
        _worker.Start();
    }

    private async Task ProcessQueueAsync()
    {
        while (!_workerTerminateSignal)
        {
            if (!HasQueuedItem)
            {
                Debug.WriteLine("No items, waiting.");
                _waitHandle.WaitOne();
                Debug.WriteLine("Waking up...");
            }
            var item = NextQueuedItem;
            if (item == null) continue;
            Debug.WriteLine(string.Format("Worker processing item"));
            await _processingActionAsync(item);
        }
    }

    public void Dispose()
    {
        if (_worker != null)
        {
            _workerTerminateSignal = true;
            _waitHandle.Set();
            if (!_worker.Join(TimeSpan.FromMinutes(1)))
            {
                Debug.WriteLine("Worker busy, aborting the thread.");
                _worker.Abort();
            }
            _worker = null;
        }
    }
}

What is the proper way to define a generic cron-job

Am going to handle a CRON job module which will be a generic module, on the job execution time shall I push the events to a queue so let the respective module will pick and do the respective operation. My question is that whether different modules can listen to the same queue? Is the below approach is correct? else can someone suggest a proper way to build a generic CRON job module that can be used by all the modules

enter image description here