相当于 C++ 中 Rust 的特定模板用法

2024-03-13

Rust 中是否有一个功能可以使这样的事情成为可能? 据我所知,Rust 的泛型函​​数不可能做到这一点,因为它们仅适用于数据类型,而不适用于值。

#include <iostream>

template<int T>
int foo(int a)
{
  return -1;
}
template<>
int foo<2>(int a)
{
  return a*a;
}
template<>
int foo<3>(int a)
{
  return a*a*a;
}

int main()
{
  std::cout << "foo<1>(3): "<<foo<1>(3) << std::endl;
  std::cout << "foo<2>(3): "<<foo<2>(3) << std::endl;
  std::cout << "foo<3>(3): "<<foo<3>(3) << std::endl;
  return 1;
}

Result:

foo<1>(3): -1
foo<2>(3): 9
foo<3>(3): 27

TL;DR:还没有,也许永远都不会。

Rust 泛型还没有 C++ 模板那么强大,而且可能永远不会那么强大。

具体来说,这里需要两个功能:

  • RFC 2000:常量泛型 https://github.com/rust-lang/rfcs/pull/2000:这将启用非类型泛型参数,
  • RFC 2000:常量泛型专业化 https://github.com/rust-lang/rfcs/blob/master/text/2000-const-generics.md#specialization-on-const-parameters.

注:尚不清楚专业化程度如何;在这种使用完全专业化的特定情况下,它应该足够了,但是尚不清楚是否会实施部分专业化以及如何实施。


还有其他缺失的部分,但与本案无关:

  • RFC 1598:通用关联类型 https://github.com/rust-lang/rfcs/pull/1598: 相当于嵌套template <...> using ... = ...;并允许模拟模板模板参数,
  • 可变参数:已经有多个 RFC,但似乎没有一个获得太多立足点。

Rust 开发者很容易被嘲笑,或者认为他们不够成熟而耸耸肩;这也是不正确的。

As I mentioned, it is not clear that Rust will ever gain some of those features, not because the developers could not implement them, they certainly could, they certainly could have already, but because there is a strong focus in doing things right1.

例如,专业化是 C++ 中的噩梦。这是未定义的行为使用一组参数 A 实例化模板,然后(或在另一个翻译单元中)以匹配 A 的方式对其进行专门化。对于函数,这通常表现为链接器选择通用版本或专用版本...随机的。调试并不好玩。

对泛型的任何修改都会对类型系统的其余部分、与其他语言功能的复杂交互以及良好类型程序的含义产生重大影响:

  • 因此他们受到严格审查,
  • 并且有强大的推动力slow和建筑逐渐地,以便一次评估这些影响、相互作用和变化。

简而言之,Rust 开发人员正在尝试构建一个原则良好的泛型系统,这并不容易。

1 There are also concerns about unnecessary complexity, so features are not added "just because", but require motivating use cases which should be compelling enough to justify the additional complexity in the language and the compiler; but that's another gate entirely.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

相当于 C++ 中 Rust 的特定模板用法 的相关文章

随机推荐