Create an alias from one type to another - c++

I'm writing some kind of DI container in c++ and I'm curious if it's possible to create aliases from one type to another in modern c++.
What I basicly want to do is to be able to call implementation constructor by it's aliased interface. Like so:
di::Register<Interface, Impl>();
di::Resolve<Interface>(); // -> Impl should be resolved
The problem is that I've not been able to find the way to alias Interface and Impl in compile time so far. I can do this using RTTI but I really don't want to use it. Is it possible at all?

By looking at the interface of your code, if you have a global state (which I don't actively recommend) you should get away with that:
using type_id_t = void(*)();
template<typename> void type_id() {}
struct di {
using create_function_t = void*(*)();
static std::unordered_map<type_id_t, create_function_t> types;
template<typename I, typename T>
static void Register() {
types.emplace(type_id<I>, []{
return static_cast<void*>(
static_cast<I*>(new T)
);
});
}
template<typename I>
static std::unique_ptr<I> Resolve() {
return std::unique_ptr<I>{static_cast<I*>(types[type_id<I>]())};
}
};
Live example

The problem is that I've not been able to find the way to alias Interface and Impl in compile time so far. I can do this using RTTI but I really don't want to use it. Is it possible at all?
There is a trick you can use to do this, assuming I understood your goal correctly. It won't look as nice as what you have there:
http://stackoverflow.com/questions/4790721/c-type-registration-at-compile-time-trick
This trick was attributed to Matt Calabrese, he described it in a Boostcon talk in like 2011.
To the best of my knowledge this trick is standards-conforming, but you must be very careful -- if you do start the registration in some header files and then continue it in some CPP files you may cause an ODR violation if you are careless.
I think you would end up with some macro like
REGISTER_PAIR( interface, impl );
and then you would have some type-alias, e.g.
get_registered_impl_t<interface>
which resolves to impl.
In the example they show how to make a list of types that is accumulated over time. In your case it would be a list of type-level "pairs" and you could search it by doing linear scan. You could try to use a fancy compile-time map data structure, but in most cases its pointless since linear scan will be fast enough, and also, the length of the list you can make is bounded by the maximum template instantiation depth of your compiler, which is typically like 100 or 200 or something. If you need larger lists there are some tricks you can use but I won't detail here.

Related

Using std::hash<uint64_t> for custom class

Do the following two return statements return the same thing?
class NonTrivialClass
{
public:
size_t hash() const
{
// variation 1
return std::hash<uint64_t>::_Do_hash(my_val_);
// variation 2, wanted to avoid creating the named object
std::hash<uint64_t> hasher;
return hasher(my_val_);
}
private:
// relevant info for hashing purposes is stored here
uint64_t my_val_;
}
I intuitively wanted to write something like
return std::hash<uint_64>(my_val_);
which did not compile (because I didn't init an instance of the struct?!). Is there a another way I am missing? Is worrying about creating the named hasher struct unneccessary?
A simpler way of writing it is using a temporary object:
return std::hash<uint64_t>{}(my_val_);
It does the same thing as your second approach.
I can't tell for sure what _Do_hash does, but in any case it is non-standard and should not be used, to avoid portability issues.
Since a google search didn't turn up any documentation of the function, I would assume that it is an implementation detail of the standard library implementation that you are using and that isn't meant to be used by user code. Therefore you shouldn't use it at all, even if you don't care about portability.
Also note that it doesn't matter for performance whether you use your approach with a named variable or my approach using a temporary. The compiler will almost surely generate identical code from it. Which you use is purely a matter of code style.

void*, extension and template. pros and kontras

Sometimes I have a problem and see 3 ways of implementing the solution. I want to know when to use which of these 3 different implementations. Below there are some exsamples, to see what I mean. I also wrote some pros/kontras which I think is correct. If something seems to be wrong, then please tell me and I'll change that.
void* example:
void method(void* value)
{
//save value as member
}
pro void*:
void* can save every type and you don't have to use templates (in headers).
kontra void*:
-when you have a list of void* you can store in index[1] another type than in index[2] which is critical, because you don't know which type it is. But with dynamic_cast you can check if you can cast it to the type or not.
-when you have a void* list with entities of the same class which have 2 variables, you can not sort by variable1 / variable2 without casting it back to the original class.
Extension exsample:
Creating a new class and extent it on another class:
class CTestClass
{
void Method1();
};
class CTest2 : CTestClass
{
//use somehow the method
};
std::vector<CTestClass> list;
pro Extension:
this way of implementing a class can be usefull, if you need a method which is in every object you need. For example you want to sort by a variable. In such a method you can make the compare.
kontra Extension:
much effort
exsample template:
template <class T>
class CTest
{
//do some stuff
};
pro template:
in a template list, you can not add different types at the same time.
kontra template:
when you have a template list of type T and T has for exsample 2 variables. You can not say: sort by variable1 or variable2 because you can not get into the class T.
As far as I know: you have to implement the template into the header file, which is ugly to see.
I hope everyone understands what I mean.
Is void* a good way to program?
Can I write templates also in .cpp files?
What do you think when to use which of this techniques? Is there some kind of rule?
The statement below is incorrect
pro void*:
void* can save every type and you don't have to use templates (in
headers).
Templates haver their closest equivalent in cross macros and not in void pointers, but exist for a different set of purposes than the mere polymorphism afforded by void pointers. Using void pointers in no way substitutes templates.
While modern programmers might not recommend about using void pointers, complaining about the (true!) potential dangers afforded, old school C-style code certainly has a use for them and this is the reason they exist. Pairing the benefits gained from void pointers with the tradeoff in performance by the C++ dynamic cast, would simply spoil the choice.
Void pointers just exist to offer limitless flexibility at managing memory when you know what you are doing and should be used only in that case. There is no comparison between them and templates.
A method that takes a void * argument should only exist when:
Case 1: The size of the passed data is known and the argument is considered as raw data. It makes no difference what that data is.
Case 2: The size of the passed data is known and you plan to convert it to a pointer of the appropriate type later (for example by some parsing, enumeration policy, known type, etc) but in order to go through some general purpose functions, libraries, APIs, you must convert it to known-length void* inbetween.

Map with comparable key types

Lately I started working on the implementation of a graph based database system. However I ran into a little problem.
The vertices in the graph are allowed to contain properties, of any type of comparable type. I was thinking about creating a map for these, as the keys are always string based. However I don't want to be bothered at all by the actually type, the only thing I want to do is compare them and still maintain safety checks. How would I go around doing so?
As I first approach I was thinking about using boost, however it'll still give me the headache of doing some manual type checking, which I absolutely do not want to do.
In Java I would do something like this, however I'm not used with these kind of things in C++.
map<String, ? extends comparable>
The reason for this is that a property can literally be any comparable type.
Not the actual answer but a requested example:
I'm used to create templates like that:
SomeClass.h:
#guards etc
template<class T> //or whatever you need
class SomeClass {
public:
SomeClass();
T content();
private:
T m_content;
}
SomeClass.cpp:
#include "SomeClass.h"
template<class T>
SomeClass::SomeClass(){
m_content = (T) 0;
}
template<class T>
T SomeClass::content(){
return T;
}
#include "SomeClass_Specializations.h"
SomeClass_Specializations.h:
#guards etc
#include "SomeClass.h"
#include "MyMagicUint.h"
//only types that behave like unsigned int may be added!
template class SomeClass<unsigned short>;
template class SomeClass<unsigned int>;
template class SomeClass<unsigned long>;
template class SomeClass<MyMagicUint>;
If you do it like that, you can specialize a long list of some common comparable types and write a comment in which you describe what other people are allowed to add to that list (in my example, unsigned int like types for some reason).
As a result, only those which are specialized here will work (since otherwise the implementation is missing), you probably have covered most of them and in the rare cases that somebody needs another specialization, he simply adds it to the list.
In the end, doing is as strict as that might not be needed, since it won't compile anyway if some forbidden action is performed, like using the <-operator when it's not defined for that type, but if you want that strict control, you can do it like that. Of course this hasn't got the dynamic control of ? extends ..., but it has control at least. Another advantage is that you can implement the code in a CPP file as usual, instead of having to put everything in the header as required for a dynamic template, that's mostly why it is my standard.
You could of course simply write the content of the specialization file directly at the bottom of the CPP instead of including another header, but I think that the specialization header is more elegant, informing prospective users what is allowed and giving them the option to add to it without taking a look at the implementation.

Static CRTP class without knowing derived type?

Given the following, working code.
#include <iostream>
template<class Detail>
class AbstractLogger
{
public:
static void log(const char* str) {
Detail::log_detailled(str);
}
};
class Logger : public AbstractLogger<Logger>
{
public:
static void log_detailled(const char* str) {
std::cerr << str << std::endl;
}
};
int main(void)
{
AbstractLogger<Logger>::log("main function running!");
return 0;
}
Now, I want to put AbstractLogger into a library, and let the library user define his own logger, like the Logger class here. This has one drawback: AbstractLogger<Logger> can not be used inside the library, since the library can not know Logger.
Notes:
Please no virtual functions or questions why not. Also, I am aware of the similar problem that "static virtual" members are invalid. Maybe, there is a workaround in CRTP :)
C++11 will be interesting, however, I need "usual" C++.
If what you mean is that you want to have a library that uses this as a logging mechanism without knowing the exact instantiating type, I would advice against it.
The only way of doing it while meeting your other requirements (i.e. no virtual functions) is that all your functions/types in the library that need to log are converted into templates that take the Logger type. The net result is that most of your interface becomes a template (although you can probably move a good amount of the implementation to non-templated code, it will make your life much harder than needed, and it will still generate a much larger binary).
If your concern with virtual functions is performance, then you should reconsider your approach and the problems it brings. In particular, logging is expensive. Most logging libraries tackle it by optimizing the non-logging case (by means of macros that avoid calling the logger if the log level/group/... are not enabled), but still leave dynamic dispatch for the actual writting. The cost of the dynamic dispatch is negligible compared with the cost of writing to the console, or a file, or even with the cost of generating the message that will be logged (I am assuming that you not only log literal strings)
The usual approach is to code against a concept, while providing helpers so that users may easily produce types that satisfy one or more of those concepts. As an example, something like boost::iterator_facade is a CRTP helper that makes it easier for a user to write an iterator. Then, that iterator can be used anywhere an iterator is accepted -- for instance in the range constructor of std::vector. Notice how that particular constructor has no foreknowledge of the user-defined type.
In your case, AbstractLogger would be the CRTP helper. The missing piece would be to define e.g. a logger concept. As a result, notice that everything that needs a logger either needs to be implemented as a template or you need a type-erasing container to hold arbitrary loggers.
Concept checks (like those provided by Boost) are convenient for this kind of programming, since they allow to represent a concept with actual code.
Template classes can't be 'put in a library' since they are instantiated by the compiler as specializations of their template parameters.
You may put parameter independent stuff used in the template implementation into a library though.

Designing a C++ library

I am in the process of designing a C++ static library.
I want to make the classes generic/configuarable so that they can support a number of data types(and I don't want to write any data type specific code in my library).
So I have templatized the classes.
But since the C++ "export" template feature is not supported by the compiler I am currently using, I am forced to provide the implementation of the classes in the header file.
I dont want to expose the implementation details of my Classes to the client code which is going to use my library.
Can you please provide me with some design alternatives to the above problem??
Prior to templates, type-agnostic C++ code had to be written using runtime polymorphism. But with templates as well, you can combine the two techniques.
For example, suppose you wanted to store values of any type, for later retrieval. Without templates, you'd have to do this:
struct PrintableThing
{
// declare abstract operations needed on the type
virtual void print(std::ostream &os) = 0;
// polymorphic base class needs virtual destructor
virtual ~PrintableThing() {}
};
class PrintableContainer
{
PrintableThing *printableThing;
public:
// various other secret stuff
void store(PrintableThing *p);
};
The user of this library would have to write their own derived version of PrintableThing by hand to wrap around their own data and implement the print function on it.
But you can wrap a template-based layer around such a system:
template <T>
struct PrintableType : PrintableThing
{
T instance;
virtual void print(std::ostream &os)
{ os << instance; }
PrintableType(const T &i)
: instance(i) {}
};
And also add a method in the header of the library, in the declaration of the PrintableContainer class:
template <class T>
void store(const T &p)
{
store(new PrintableType(p));
}
This acts as the bridge between templates and runtime polymorphism, compile-time binding to the << operator to implement print, and to the copy-constructor also (and of course also forwarding to the nested instance's destructor).
In this way, you can write a library entirely based on runtime polymorphism, with the implementation capable of being hidden away in the source of the library, but with a little bit of template "sugar" added to make it convenient to use.
Whether this is worth the trouble will depend on your needs. It has a purely technical benefit in that runtime polymorphism is sometimes exactly what you need, in itself. On the downside, you will undoubtedly reduce the compiler's ability to inline effectively. On the upside, your compile times and binary code bloat may go down.
Examples are std::tr1::function and boost::any, which have a very clean, modern C++ template-based front end but work behind the scenes as runtime polymorphic containers.
I've got some news for you, buddy. Even with export, you'd still have to release all of your template code -- export just makes it that you don't have to put the definitions in a header file. You're totally stuck. The only technique you can use is split off some functions that are non-templates and put them into a different class. But that's ugly, and usually involves void* and placement new and delete. That's just the nature of the beast.
You can try to obfuscate your code - but you have little choice in C++03 asides from including template code in header files.
Vandevoorde does describe another technique in his book: Explicit instantiation - but that entails having to explicitly instantiate all possible useful combinations.
But for the most comprehensive review of this topic read chapter 6 from C++ Templates: The Complete Guide.
Edit (in response to your comment): You have two options for writing generic code without using templates:
1) Preprocessor - still requires header files
2) using void* - yuk - incredibly unsafe
So no, i do not recommend not using templates for solving problems that templates were specifically designed (albeit somewhat flawed) for.
One problem with templates is that they require compiled code. You never know how the end-user will specialize/instantiate your templates, so your dll-file would have to contain all possible template specializations in compiled form. This means that to export pair<X,Y> template you would have to force the compilication of pair<int,float>, pair<int,string>, pair<string,HWND> and so on... to infinity..
I guess more practical solution for you would be to un-template private/hidden code. You can create special internal functions that would only be compiled for single template specialization. In the following example internal_foo-function is never called from MyClass where A is not int.
template<class A>
class MyClass
{
int a;
float b;
A c;
int foo(string param1);
{
((MyClass<int>*)this)->internal_foo(param1);
}
int internal_foo(string param1); // only called on MyClass<int> instances
};
template<>
__declspec(dllexport) int MyClass<int>::internal_foo(string param1)
{
... secret code ...
}
This of course is a hack. When using it you should be extra careful not to use member variable "c", because it's not always integer (even though internal_foo thinks that it is). And you can't even guard yourself with assertions. C++ allows you to shoot yourself in the foot, and gives you no indications about it until it's too late.
PS. I haven't tested this code so it might require some fine tuning. Not sure for example if __declspec(dllimport) is needed in order for compiler to find internal_foo function from dll-file...
With templates you cannot avoid shipping the code (unless your code only works with a fixed set of types, in which case you can explicitly instantiate). Where I work we have a library that must work on POD types (CORBA/DDS/HLA data definitions), so at the end we ship templates.
The templates delegate most of the code to non-templated code that is shipped in binary form. In some cases, work must be done directly in the types that were passed to the template, and cannot thus be delegated to non-templated code, so it is not a perfect solution, but it hides enough part of the code to make our CEO happy (the people in charge of the project would gladly provide all the code in templates).
As Neil points in a comment to the question, in the vast majority of cases there is nothing magical in the code that could not be rewritten by others.