【问题标题】:Why does this partial specialization of a template friend function work?为什么模板友元函数的这种部分特化有效?
【发布时间】:2017-09-11 08:52:08
【问题描述】:

我正在编写实现向量和矩阵的简单类,作为学习 OpenGL 的一部分。我有看起来像这样的矩阵和向量类:

// Forward declarations
template <typename T, size_t N/*len*/> struct vec;
template<typename T, size_t N /*rows*/, size_t M /*cols*/> struct mat;

// Forward declare *operator for matrix
// (NxM) matrix multiplied by (MxP) matrix yields (NxP) matrix
mat<T, N, P> operator* (const mat<T, N, M>& A, const mat<T, M, P>& B);

template <typename T, size_t N>
struct vec {
    public:
        vec() {}
        virtual ~vec() {}
    private:
        T[N] m_data;
};

template <typename T, size_t N, size_t M>
struct mat {
    public:
        mat() {}
        virtual ~mat() {}
        // This is where it gets interesting. By my reading of the rules
        // of C++11, this counts as a partial specialization of the 
        // operator template, and should not work. 
        // However, it compiles just fine!
        template <size_t n, size_t m, size_t p> 
        friend mat<T, n, p> operator* (const mat<T, n, m>& A,
                                         const mat<T, m, p> &B); 
        // Implementation appears later in the same header file. 
    private:
        T[N*M] m_data;
};

我将 * 运算符声明为朋友,因为我希望它可以访问内部 m_data 成员,但我不希望 'mat' 和 'vec' 的用户知道内部。

这编译并运行得很好。我对该矩阵乘法进行了单元测试,它工作得很好。但是,我不知道为什么它甚至可以编译,更不用说运行了。根据我对C++模板规则的阅读,*运算符的声明算作函数模板的部分特化,是非法的。

我在这里错过了什么?

【问题讨论】:

  • 请添加您用于成功构建程序的其余代码。

标签: c++11 templates template-meta-programming template-specialization friend-function


【解决方案1】:

原来这确实*NOT* 编译。我认为它正在编译,因为当我认为我没有在单元测试中调用模板流运算符时。

抱歉这个愚蠢的问题!

【讨论】:

    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    相关资源
    最近更新 更多