defining inline functions under template class definition

I'm trying to make an inline definition of a template class ctor under the class definition (I know you can do it inside, but I prefer to do it outside in the header file). However, MSVC is telling me that Matrix requires a template argument list in the ctor definition... I can easily solve this by defining the function inside the class (it still will be inlined), but I would prefer to do it outside due to esthetic reasons. Is there a way to solve this?

// .hpp 

#pragma once

template <typename T, size_t rows, size_t cols>
class Matrix {
private:
    constexpr size_t m_size = rows * cols;
    std::array<T, m_size> m_arr;
public:
    __forceinline Matrix();
};

Matrix::Matrix() : m_arr() { // this gives errors
    // do ctor stuff
}

However, MSVC is telling me that Matrix requires a template argument list in the ctor definition...

Matrix::Matrix() : m_arr() { // this gives errors

You missed the template specification that should be given for the definition, that's probably what the compiler message tells you:

template <typename T, size_t rows, size_t cols> // <<<< This!
Matrix<T,rows,cols>::Matrix() : m_arr() { 
   // ^^^^^^^^^^^^^ ... and this
    // do ctor stuff
}

... but I prefer to do it outside in the header file ...

To do so put the definition into a file that isn't atomatically picked up as a translation unit by your build system (eg some extension like .icc or .tcc ), and #include that one at the end of your header containing the template class declarations.

The complete code should look like

Matrix.hpp

#pragma once
#include <cstddef>

template <typename T, std::size_t rows, std::size_t cols>
class Matrix {
private:
    constexpr static std::size_t m_size = rows * cols;
    std::array<T, m_size> m_arr;
public:
    __forceinline Matrix();
};

#include "Matrix.icc"

Matrix.icc

template <typename T, std::size_t rows, std::size_t cols>
Matrix<T,rows,cols>::Matrix() : m_arr() { 
    // do ctor stuff
}
链接地址: http://www.djcxy.com/p/37142.html

上一篇: 模板中关键字'typename'和'class'的区别?

下一篇: 在模板类定义下定义内联函数