template specialization question
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.
Re: template specialization question
Quote:
Originally Posted by
drwowe
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.
Boost has an is_arithmetic<T> template.
http://www.boost.org/doc/libs/1_39_0...rithmetic.html
Regards,
Paul McKenzie
Re: template specialization question
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?
Re: template specialization question
You can try this:
Code:
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.
Re: template specialization question
If your compiler support the TR1 extensions to the language then the <type_traits> header is available.
The compile time error can be generated by using a 'static assert'
static_assert is not supported by current compilers (as far as I know), but it can be emulated. See http://www.csn.ul.ie/~caolan/Fragments/C++StaticAssert.html or the Boost version can be used.