c++ - 在模板类定义下定义内联函数

标签 c++ templates

我正在尝试在类定义下对模板类构造函数进行内联定义(我知道您可以在内部执行此操作,但我更喜欢在头文件的外部执行此操作)。然而,MSVC 告诉我 Matrix 需要在 ctor 定义中使用模板参数列表...我可以通过在类内部定义函数来轻松解决这个问题(它仍然会被内联),但我会由于美观原因,更喜欢在室外进行。有办法解决这个问题吗?

// .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

您错过了应该为定义给出的模板规范,这可能是编译器消息告诉您的内容:

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 ...

为此,请将定义放入一个文件中,该文件不会被构建系统自动拾取为翻译单元(例如 .icc.tcc 等扩展名) >),以及位于 header 末尾的包含模板类声明的 #include

完整的代码应该是这样的

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
}

关于c++ - 在模板类定义下定义内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48026758/

相关文章:

c++ - 返回带有 bool 结果标志的值的标准模板

c++ - 如何对齐人脸图像c++ opencv

c++ - 这是lambda法律模板语法吗?

c++ - universal dynamic_cast<void*> 等价于多态和非多态类型

c++11 函数调用中的 vector 初始化

c++ - 在 C++ 中交换未初始化的成员是否安全?

python - Google App Engine 使用数组将模板变量传递到 View 中

c# - 如何检查 T4 模板文件中实体属性的数据类型

c++ - 扩展类模板

c++ - 如何使用 boost.program_options 处理多个语法命令行参数