Reputation: 2040
I'm trying to write a fixed point arithmetic class where point position and underlying type are templates
template <int P, typename T>
class basic_fixedpoint{
//stuff
};
I also want to expose a single templated implicit constructor that is then specialized for various types
//inside basic_fixedpoint
template <typename U>
basic_fixedpoint(const U& arg);
Elsewhere I will implement specializations for int, float, double, etc. However, I also want to provide a generic specialization for any type of basic_fixedpoint with different P and T. How can I do this as a templated template specialization?
template <int P, typename T> //for the class whose constructor i specialize
template <int OP, typename OT> //for the parameters of the argument
basic_fixedpoint<P, T>::basic_fixedpoint<basic_fixedpoint<OP, OT> >(const basic_fixedpoint<OP, OT>& arg)
: /*init things here*/ {} // this fails
I'm trying to avoid overloading the constructor so as to present a single interface in the header, telling the user "This class will cleanly construct itself from whatever type you give it, or it will fail to compile and give you an incomprehensible paragraph long error message"
As a sub question: This class also implements the basic operator int(), operator float(), operator double() conversions, and also overloaded arithmetic operators and math functions are provided. Naturally, whenever I try to invoke anything with this class, the call is ambiguous because every possibility is available.
How can I keep this class fully flexible, but still allow pain-free unambiguous overloaded function calls that behave properly (rather than always converting my class to a double and back)?
Upvotes: 1
Views: 263
Reputation: 208456
I think you may want to reconsider what you really want. Implicit conversions are not always a good idea (they are a bad idea more often than not) and a class that can be implicitly convertible to and from the same types is always a bad idea (it will cause ambiguity errors whenever you use that class and the convertible to/from type together as it could go both ways.
You should go back to the design board and decide what needs to be implicit and what can be named or explicit conversions.
Besides that, and regarding your particular question, you cannot specialize that constructor. Functions (and constructors among them) can only be fully specialized, and in particular you cannot specialize a template function that is a member of a template class without also fully specializing the class template. I.e. you can specialize:
basic_fixedpoint<5,int>::basic_fixed_point<int>(int)
but you cannot specialize:
template <int N, typename T>
basic_fixed_point<N,T>::basic_fixed_point<int>(int)
As N
and T
are not bound in that specialization.
Upvotes: 2