类定义中构造函数的模板专用化

Template specialization of constructor within class definition

本文关键字:专用 定义 构造函数      更新时间:2023-10-16

尽管我试图像在其他地方一样复制,但我无法获得类内构造函数模板专门化的正确语法。

考虑以下类别:

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)上的模板。