【问题标题】:Template specialization of constructor within class definition类定义中构造函数的模板特化
【发布时间】: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


    【解决方案1】:

    你不能。专业化需要一个完整的、定义明确的类型。所以当编译器遇到你的Point&lt;0,0&gt;::Point()定义时,模板化类型Point还是不完整的。您要做的是在提出规则之前解释例外情况。

    在您提供的示例中,构造函数不是特化,而是附加类型 (C) 上的模板。

    【讨论】:

    • 这解释了“不完整类型”错误。但是我很好奇为什么编译器将其视为不完整的 - 肯定意味着它需要整数?
    • 其他是语法错误:你不能在结构中进行专门化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多