避免模板参数完全替代 我有一个可以接受算术类型和std :: Complext的类。该类简化的代码是 #include

问题描述 投票:0回答:2
#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具有typedef

value_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
}

谨慎地,我希望替换t忽略此功能,以防t是t的。有可能吗?如果没有,我该如何规避?
    
您在正确的轨道上,有

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;
c++ templates substitution overload-resolution
2个回答
1
投票

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>

但是您需要在使用时将其放入其中。我只是硬编码

1
投票
,但是您必须将新的模板参数添加到

struct nullptr_value_type {using value_type = std::nullptr_t;}; 或使模板成员函数

	

© www.soinside.com 2019 - 2024. All rights reserved.