Reputation: 946
I can't get the syntax right for in-class constructor template specialization, despite trying to copy exactly as it is done elsewhere.
Consider the following class:
template<int A, int B>
struct Point {
const int x;
const int y;
Point() : x(A), y(B) { std::cout << "Constructing arbitrary point" << std::endl; }
void print() { std::cout << "Coords: " << x << ", " << y << std::endl; }
};
Implementing specialized template-based constructors outside of the class definition, namely
template<int A, int B>
struct Point {
const int x;
const int y;
Point() : x(A), y(B) { std::cout << "Constructing arbitrary point" << std::endl; }
void print() { std::cout << "Coords: " << x << ", " << y << std::endl; }
};
template<> Point<0, 0>::Point() : x(0), y(0) { std::cout << "Constructing origin" << std::endl; }
works just fine. However, when I try to do so within the class definition itself by adding the line
template<int A, int B>
struct Point {
const int x;
const int y;
Point() : x(A), y(B) { std::cout << "Constructing arbitrary point" << std::endl; }
template<> Point<0, 0>::Point() : x(0), y(0) { std::cout << "Constructing origin" << std::endl; }
void print() { std::cout << "Coords: " << x << ", " << y << std::endl; }
};
I receive the following errors:
9:14: error: explicit specialization in non-namespace scope 'struct Point<A, B>'
9:35: error: invalid use of incomplete type 'struct Point<0, 0>'
4:8: error: declaration of 'struct Point<0, 0>'
Another SO template specialisation question I tried to copy: explicit-template-specialization-for-constructor
Upvotes: 2
Views: 409
Reputation: 40070
You can't. Specialization required a complete, well-defined type. So when the compiler encounters your Point<0,0>::Point()
definition, the templated type Point
is still incomplete. What you're trying to do is explaining the exception before you present the rule.
In the example you provided, the constructor is not a specialization, rather a template on a additional type (C
).
Upvotes: 2