Suppose I've got a template, and I want to only instantiate to a specific list of types, and nothing else, like this:
template<typename T> T addone(T x) {
return x+1;
}
The problem I have is that I only want functions of actual numbers to be created. I don't want it going crazy and trying to do pointer arithmetic and every other **** thing that has a + operator. I only want:
int addone(int x)
unsigned int addone(unsigned int x)
long addone(long x)
unsigned long addone(unsigned long x)
// etc, for short, char, ...
I don't want:
T* addone(T* stupidpointer)
Is there a way to do specialization such that nothing except specialized templates can be instantiated implicitly? This is causing me headaches in combination with overload resolution because it keeps trying to instantiate my templates to stupid things to resolve the overload.
Suppose I've got a template, and I want to only instantiate to a specific list of types, and nothing else, like this:
template<typename T> T addone(T x) {
return x+1;
}
The problem I have is that I only want functions of actual numbers to be created. I don't want it going crazy and trying to do pointer arithmetic and every other **** thing that has a + operator.
Thanks! It seems like it's on the right track. All the examples in the documentation provide generic template functions, and the use the traits to create optimized functions for certain kinds of types.
Is there a way to adapt this technique so the generic functions are never created in the first place?
template<typename T>
T addone(T x)
{
return x+1;
}
template <typename T>
T* addone(T* p)
{
// error at compile time, only if the method is called
return 1+1;
// or, at runtime
// assert(0);
return NULL;
}
The drawback with this code is that the error message is not very appropriate. I suggest you to consult this book Andrei Alexandrescu - "Modern C++ Design: Generic Programming and Design Patterns Applied" - it may help you to find a better solution.
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
Bookmarks