我想专门化类模板的成员函数,如下所示:
#include <concepts>
template <typename T>
struct S {
void f();
};
template <typename T>
void S<T>::f() {
}
// (0) This is fine.
template <>
void S<int>::f() {
}
// (1) This triggers an error.
template <std::integral T>
void S<T>::f() {
}
特化 (0) 很好,但特化 f()
仅适用于 int
类型。相反,我想将其专门化,例如,针对任何整数类型,如(1)中所示。使用 C++20 概念可以实现这一点吗?请注意,std::integral
只是一个示例,我的具体案例使用了用户定义的概念。
最佳答案
只需使用尾随的 require 子句即可。编译器会选择最受约束的函数:
#include <concepts>
#include <iostream>
template <typename T>
struct S {
void f();
void f() requires std::integral<T>;
};
template <typename T>
void S<T>::f() {
std::cout << "general\n";
}
template <typename T>
void S<T>::f() requires std::integral<T> {
std::cout << "constrained\n";
};
int main() {
S<int> x;
S<double> y;
x.f(); // prints constrained
y.f(); // prints general
return 0;
}
关于c++ - 使用 C++20 概念专门化类模板的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71025802/