有没有办法让这个C++模板工作?

huangapple go评论66阅读模式
英文:

Is there any way to make this template in cpp work?

问题

以下是翻译好的部分:

完整的代码在这里:https://pastebin.com/XXutDDjP

整个项目可能会有点混乱,但我在以下部分感到困惑。

看看这段代码:

template <typename T>
T myMax(T x, T y) {
  return (x > y) ? x : y;
}

例如,这段代码匹配了以下参数:

myMax(int x, int y), myMax(char x, char y),...

所以,T 可以替代任何数据类型,如 chardoubleintfloat,...

但是,我想要使用类似这样的东西:

template <typename T>
int myMax(int A[T][T], int n) {
  // ...
}

这样它就可以用于所有类型为 A[T][T] 的矩阵,
myMax(A[5][5], 2)myMax(A[7][7], 5),...

英文:

Full Code is here: https://pastebin.com/XXutDDjP

The whole project can get a bit messy to post here, but I am confused in the following part.

Check out this code:

template &lt;typename T&gt;
T myMax(T x, T y) {
  return (x &gt; y) ? x : y;
}

For example, this code matches the arguments,

myMax(int x, int y), myMax(char x, char y), …

so, T can replace any data-type like char, double, int, float, …

But, I want to use something like:

template &lt;typename T&gt;
int myMax(int A[T][T], int n) {
  // ...
}

So that it can be used for all matrices of type A[T][T],
myMax(A[5][5], 2), myMax(A[7][7], 5), …

答案1

得分: 1

为了允许使用C风格数组、std::arraystd::vector以及其他可能自定义的矩阵类,这些类可能会重载operator[],我会使用:

template <typename T>
int myMax(T const& matrix, int n) {
  // ...
}
英文:

To allow usage of C-style arrays, std::array, std::vector and other possible custom Matrix classes that overload operator[], I'd use:

template &lt;typename T&gt;
int myMax(T const&amp; matrix, int n) {
  // ...
}

答案2

得分: 0

只需将typename更改为size_t

template<size_t T>
int myMax(int A[T][T], int n)
{
}
英文:

just change typename to size_t:

template&lt;size_t T&gt;
int myMax(int A[T][T], int n)
{
}

huangapple
  • 本文由 发表于 2020年1月6日 15:37:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定