英文:
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<T, std::string>
.
To constrain R and C, just add the appropriate conditions to the requires clause:
template<typename T, unsigned R, unsigned C>
requires (StringOrArithmeticType<T> && (R > 1) && (C > 1))
class matrix { ... };
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论