类定义中构造函数的模板专用化
Template specialization of constructor within class definition
尽管我试图像在其他地方一样复制,但我无法获得类内构造函数模板专门化的正确语法。
考虑以下类别:
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模板专业化问题:构造函数的显式模板专用化
你不能。专业化需要一个完整的、定义明确的类型。因此,当编译器遇到Point<0,0>::Point()
定义时,模板化的类型Point
仍然是不完整的。您要做的是在提出规则之前解释异常。
在您提供的示例中,构造函数不是专门化,而是附加类型(C
)上的模板。
相关文章:
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- C++模板专用化 - 无法匹配函数定义
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 为什么模板专用化需要内联定义?
- 模板专用化会导致未定义的引用错误
- 对专用模板成员的未定义引用
- 在模板类内部定义的枚举上的嵌套类的部分专用化
- 没有针对完全专用模板类的外联虚拟方法定义
- 使用模板模板参数进行模板定义的函数专用化
- 如何从具有专用化的类模板定义静态成员变量?
- 如何为模板化类的模板化函数定义模板专用化
- C++模板专用化成员函数的定义
- 仅为某些模板专用化定义转换运算符:预期类型/预期类型说明符
- 如何在另一个类模板中定义完全专用类的构造函数
- C++跨文件共享的模板专用化定义
- 如何专用/分配自定义内存位置,以便可以在C 中编辑该位置
- 元组的定义和初始化,其组件属于同一模板化类,但具有不同的专用化
- 在子类中定义可变参数函数专用化
- 为类模板的单个成员定义专用化
- UE4自定义专用服务器(碰撞,命中框)