#include <complex>
template<typename T> struct is_complex : std::false_type {};
template<typename T> struct is_complex<std::complex<T>> : std::true_type {};
template<class T>
struct Foo {
void foo(typename T::value_type t)
requires (is_complex<T>::value) {
}
};
现在,我想采用内部类型
std::complex
并将其用作foo
函数中的参数类型。例如,如果t是std::complex<double>
,那么我希望参数类型为
double
.仅当t确实是
std::complex
时,才能可用。
我认为我可以将typename T::value_type
用作参数类型,因为
std::complex
具有typedefvalue_type
。另外,我认为使用
requires
在此功能中可以避免在此功能中替换t,以防t td ::复杂。愚蠢的我
问题是,每当我创建Foo<FundamentalType>
代码中断时,基本面没有::value_type
。
int main() {
Foo<int> obj; // Breaks the code.
//obj.foo(4); // Function shouldn't be considered in overload resolution ideally...
Foo<std::complex<int>> obj2; // Works
obj2.foo(4); // Works as expected
}
您在正确的轨道上,有
std::complex
:您在这里也希望这样的类型不同。例如,
is_complex
template<typename T> struct complex_value_type {};
template<typename T> struct complex_value_type<std::complex<T>> { using type = T; };
template<typename T>
using complex_value_type_t = typename complex_value_type<T>::type;
complex_value_type_t<T>
那时不是绝对必要的;它已经被仅针对template<class T>
struct Foo {
template<typename T_ = T>
void foo(complex_value_type_t<T_> t)
requires (is_complex<T_>::value) {
}
};
的定义。
您只需要放入其中的类型,直到可以禁用函数为止。 我会这样做:
requires
complex_value_type_t<T>
将模板类作为模板参数。
complex<T>
但是您需要在使用时将其放入其中。我只是硬编码struct nullptr_value_type {using value_type = std::nullptr_t;};
或使模板成员函数