假設我正在撰寫一個模板函式,它想要呼叫operator =它的模板引數并且不關心它是否回傳新值(型別T)、avoid或其他任何值。例如:
template<class T>
void incrementAll(T *array, int size, T value) {
for (int i = 0; i < size; i) {
array[i] = value;
}
}
我想對這個函式有一個約束:讓它需要一個concepton T。但是,我找不到對回傳型別沒有任何要求的。我能想到的唯一想法是std::convertible_to<void>(因為我們可以將任何值轉換為 void,對嗎?),但它失敗了:
#include <concepts>
template<class T>
concept Incrementable = requires(T a, T b) {
{a = b} -> std::convertible_to<void>;
};
template<class T> requires Incrementable<T>
void incrementAll(T *array, int size, T value) {
for (int i = 0; i < size; i) {
array[i] = value;
}
}
int main() {
int arr[] = {1};
incrementAll(arr, 1, 1);
}
nikolay@KoLin:~$ g another_tmp.cpp -std=c 20 -fconcepts-diagnostics-depth=10
another_tmp.cpp: In function ‘int main()’:
another_tmp.cpp:17:21: error: no matching function for call to ‘incrementAll(int [1], int, int)’
17 | incrementAll(arr, 1, 1);
| ~~~~~~~~~~~~^~~~~~~~~~~
another_tmp.cpp:9:6: note: candidate: ‘template<class T> requires Incrementable<T> void incrementAll(T*, int, T)’
9 | void incrementAll(T *array, int size, T value) {
| ^~~~~~~~~~~~
another_tmp.cpp:9:6: note: template argument deduction/substitution failed:
another_tmp.cpp:9:6: note: constraints not satisfied
another_tmp.cpp: In substitution of ‘template<class T> requires Incrementable<T> void incrementAll(T*, int, T) [with T = int]’:
another_tmp.cpp:17:14: required from here
another_tmp.cpp:4:9: required for the satisfaction of ‘Incrementable<T>’ [with T = int]
another_tmp.cpp:4:25: in requirements with ‘T a’, ‘T b’ [with T = int]
another_tmp.cpp:5:12: note: ‘a = b’ does not satisfy return-type-requirement, because
5 | {a = b} -> std::convertible_to<void>;
| ~~^~~~
another_tmp.cpp:5:10: error: deduced expression type does not satisfy placeholder constraints
5 | {a = b} -> std::convertible_to<void>;
| ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
another_tmp.cpp:5:10: note: constraints not satisfied
In file included from another_tmp.cpp:1:
/usr/include/c /11.2.0/concepts:72:13: required for the satisfaction of ‘convertible_to<decltype(auto) [requires std::convertible_to<<placeholder>, void>], void>’ [with decltype(auto) [requires std::convertible_to<<placeholder>, void>] = int&]
/usr/include/c /11.2.0/concepts:72:30: note: the expression ‘is_convertible_v<_From, _To> [with _From = int&; _To = void]’ evaluated to ‘false’
72 | concept convertible_to = is_convertible_v<_From, _To>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
那么,在這里定義的正確概念是什么?
uj5u.com熱心網友回復:
如果您不關心它的回傳型別是什么,那么您可以簡單地使用-requires子句來要求運算式a = b格式正確:
template<class T>
concept Incrementable = requires(T a, T b) {
a = b;
};
T&不過這樣的概念對于可遞增型別來說似乎太松散了,要求回傳型別為like{a = b} -> same_as<T&>并命名之類的似乎更合適AdditionAssignable。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438902.html
上一篇:如何在類模板中專門化模板化方法?
