gpt4 book ai didi

c++ - 当作为参数传入时,是否可以让编译器指定模板类参数?

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:32 25 4
gpt4 key购买 nike

请考虑以下事项:我正在用 C++ 编写 Matrix 类,它看起来像这样:

template<unsigned rows, unsigned cols>
class matrix
{
...
};

现在,在编写乘法方法时,我遇到了一个问题:左侧 - “this” - 矩阵的列数必须与右侧 - “o” - 矩阵的行数相同,但 o 的列数必须相同有,无关紧要,见下文:

const matrix<rows, rows> mul(const matrix<cols, /*This can be anything*/>&& o)
{
...
}

我的问题是,有没有什么方法可以告诉编译器,它应该将 o 的模板参数作为其未知的第二个参数?

最佳答案

is there any way to tell the compiler, that it should take the template argument of o for its unknown second argument?

是的,这正是模板为您所做的:)只需将 mul() 编写为成员函数模板,而不是成员函数

template<unsigned rows, unsigned cols>
class matrix
{
...

template <unsigned rhsRows>
matrix<rows, rhsRows> mul(const matrix<cols, rhsRows>& o) const
{
...
}
};

注意:const 被移动到成员函数模板 const 而不是作为返回值的 const,因为在那里它可以禁用移动语义,因为乘法矩阵的语义在返回结果时不应更改任何操作数。

关于c++ - 当作为参数传入时,是否可以让编译器指定模板类参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51988633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com