I am writing a library for efficient number processing. I have to support different types of numbers — double, complex, or even custom_matrix maybe. For performance reasons I’ve decided to compile separate library file for each number kind, so that compiler may use aggressive optimizations for arithmetic operations and function calls. Now I have two options — either to write template classes with parameter number_type, e.g.
template <typename valueType>
class Worker {
valueType process(valueType value);
};
or to typedef number kind in project-wide header file, e.g.
in 'project.hpp':
namespace myProject {
typedef double valueType;
}
in 'worker.hpp':
#include "project.hpp"
namespace myProject {
class Worker {
valueType process(valueType value);
};
}
Personally I can’t accept either way: template-based code is driving me insane with tons of redundant template and typename keywords, meanwhile typedef-based code can’t be compiled in single library file (linking fails because of duplicate names), so I can’t use different number types in one program.
So the question is: am I missing something? Is there a better/cleaner way to accomplish my task?
EDIT: I have to use double and complex code in one application at the same time.
EDIT2: Okay, to make things clear: I’m developing an arithmetic expression parsing engine for iOS app. Therefore I’m limited to C/C++/Objective-C, and the performance is crucial.
Also, I feel comfortable in using templates in common circumstances. In my situation all my source files are full of angle brackets and template/typename keywords. It’s simply annoying and distracts me from writing stuff that matters.
I guess I’ll use templates, since there is no better solution as far as I can see.
You should use the templates. If you insist on doing the absolute maximum amount of work at compile time instead of at run time, and your language of choice is C++, you will use template programming.
It’s a mess of less-than and greater-than signs, confusing error messages, and
typenamekeywords (plus don’t get me started on explicit instantiations when you don’t want to define your whole class in the header!), but it’s the mess we’ve got.EDIT: there is a third option, in the form of preprocessing – you could run the same code through the preprocessor twice, putting the symbols in a different namespace each time, to get the same effect as the
typedefversion without the symbol collisions.