我在計算機科學課上分配了一個任務,String<T>用 C 實作一個類,該類的print方法會拋出例外,除非T = char. 所以我用template<typename T> class String這種方式定義了一個方法:
void print(std::basic_ostream<T> stream) {
throw StringTypeError("Can't print with these types");
}
并像這樣定義了一個專業化:
template<>
void String<char>::print(std::basic_ostream<char> stream) {
for(unsigned long i = 0; i < size; i )
stream << charAt(i);
}
這完全有效,但是我最近發現了一些概念,并決定允許使用print()for 任何型別,它可以是<</>>到 IO 流中。我創建了一個小概念:
template<typename T>
concept IO = requires(T a) {
std::cout << a;
std::cin >> a;
};
并試圖以這種方式改變我的專業化:
template<IO T>
void String<T>::print(std::basic_ostream<T> stream) {
for(unsigned long i = 0; i < size; i )
stream << charAt(i);
}
但是編譯器拒絕了“型別約束在模板重新宣告中不同”錯誤。
我犯了一個可以糾正的錯誤,還是不可能以這種方式使用概念?(如果是這樣,是否有任何類似概念的替代方案?)
uj5u.com熱心網友回復:
有沒有類似概念的替代品?
有一個適合這項作業的工具,一個特別好的新特性,帶有概念及其相關的要求子句,這是 C 20 之前的 SFINAE 不可能實作的,即可以宣告類模板的非模板成員函式帶有要求子句。print這意味著您可以在主模板中定義兩個互斥的成員函式:
template<typename T>
class String {
void print(std::basic_ostream<T>&) requires (!IO<T>) {
throw StringTypeError("Can't print with these types");
}
void print(std::basic_ostream<T>& stream) requires (IO<T>) {
for(unsigned long i = 0; i < size; i )
stream << charAt(i);
}
// ...
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/537520.html
上一篇:HTML模板和選擇器
下一篇:如何創建HTML模板?
