如何将模板限制为特定类型

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

How to constrain a template to a specific type

问题

  1. 我在C++中尝试模板编程,其中我为矩阵编写了一个模板。
  2. ```cpp
  3. template <
  4. typename T,
  5. unsigned int R, unsigned int C>
  6. requires StringOrArithmeticType<T>
  7. class matrix {
  8. ...
  9. };

通过类型特征,我可以将T约束为浮点型和整数类型。如何使用特定类型,比如字符串,来实现这个约束呢?

  1. template <typename T>
  2. concept StringOrArithmeticType =
  3. is_integral_v<T> || is_floating_point_v<T> || is_string<T>::value;

因此,我实现了自己的is_string。在类型特征中,我找不到有用的内容。在这里,我需要一些帮助,应该如何解决这个问题?另外,我想设置R和C必须大于1的约束。

  1. <details>
  2. <summary>英文:</summary>
  3. I am trying out template programming in C++ where I programmed a template for matrix.

template <
typename T,
unsigned int R, unsigned int C>
requires StringOrArithmeticType<T>
class matrix {
...
};

  1. From the type traits I could constrain the T to floating point and integral types. How can I do it with for example a specific type like string?

template <typename T>
concept StringOrArithmeticType =
is_integral_v<T> || is_floating_point_v<T> || is_string<T>::value;

  1. So I implemented my own is_string. In type traits I could not find something helpful? Here I need some help, how should I solve this problem? Also, I would like to set the constrain that R and C must be greater than 1.
  2. </details>
  3. # 答案1
  4. **得分**: 0
  5. 要检查类型是否为字符串,请使用 `std::is_same_v<T, std::string>`
  6. 要约束 R C,只需在 requires 子句中添加适当的条件:
  7. ```cpp
  8. template<typename T, unsigned R, unsigned C>
  9. requires (StringOrArithmeticType<T> && (R > 1) && (C > 1))
  10. class matrix { ... };
英文:

To check if the type is a string, use std::is_same_v&lt;T, std::string&gt;.

To constrain R and C, just add the appropriate conditions to the requires clause:

  1. template&lt;typename T, unsigned R, unsigned C&gt;
  2. requires (StringOrArithmeticType&lt;T&gt; &amp;&amp; (R &gt; 1) &amp;&amp; (C &gt; 1))
  3. class matrix { ... };

huangapple
  • 本文由 发表于 2023年2月8日 21:42:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386665.html
匿名

发表评论

匿名网友

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

确定