【发布时间】:2015-11-24 13:08:11
【问题描述】:
尽管尝试完全按照其他地方的方式进行复制,但我无法为类内构造函数模板特化获得正确的语法。
考虑以下类:
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<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; }
工作得很好。但是,当我尝试通过添加行在类定义本身中这样做时
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; }
};
我收到以下错误:
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>'
我试图复制的另一个 SO 模板专业化问题: explicit-template-specialization-for-constructor
【问题讨论】:
标签: c++ templates constructor template-specialization