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

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

How to constrain a template to a specific type

问题

我在C++中尝试模板编程,其中我为矩阵编写了一个模板。

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

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

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

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


<details>
<summary>英文:</summary>

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 {
...
};

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;

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.

</details>


# 答案1
**得分**: 0

要检查类型是否为字符串,请使用 `std::is_same_v<T, std::string>`。

要约束 R 和 C,只需在 requires 子句中添加适当的条件:

```cpp
template<typename T, unsigned R, unsigned C>
requires (StringOrArithmeticType<T> && (R > 1) && (C > 1))
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:

template&lt;typename T, unsigned R, unsigned C&gt;
requires (StringOrArithmeticType&lt;T&gt; &amp;&amp; (R &gt; 1) &amp;&amp; (C &gt; 1))
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:

确定