c++ - 仅当类型为 std::complex 时才缩放

标签 c++ c++11 templates

我有以下模板功能:

template <typename T0>
struct ComplexTypeTraits
{
    using type = T0;
};

template <typename T0>
struct ComplexTypeTraits<std::complex<T0> >
{
    using type = T0;
};
template<typename T>
void myFunction(T& out, const T & in)
{
    using T1 = typename ComplexTypeTraits<T>::type; // will be 'T' for std::complex<T>

    out = in;
    if(std::is_same<T, T1>::value == false)
    {// if the type is std::complex<T>, do a scaling
        const T1 theta = M_PI/2.0;
        const T y(std::cos(theta),-1*std::sin(theta));
        out = out*y;
    }
}

以下对该函数的调用有效:
    std::complex<float> in(10, 5);
    std::complex<float> out = 0;
    myFunction<std::complex<float>>(out, in);
    std::cout<<"out is: "<<out<<std::endl;

但是,当我以下列方式调用函数时,会给出错误“标量初始化程序中的多余元素。
float in = 10;
float out = 0;
myFunction<float>(out, in);

基本上,如果参数类型是 std::complex,我想做一个缩放。如何解决问题?
std::cout<<"输出为:"<

最佳答案

该函数无法编译,因为 const T y(std::cos(theta),-1*std::sin(theta)); 行仍然需要有效;不是T = float .

如果:

if constexpr (std::is_same<T, T1>::value == false)

如果你不能使用 C++17,你可以使用标签调度:
template<typename T>
struct is_complex : std::false_type {};
template<typename T>
struct is_complex<std::complex<T>> : std::true_type {};

template<typename T>
void myFunction_impl(T& out, const T& in, std::false_type)
{
    // Nothing to do
}

template<typename T>
void myFunction_impl(T& out, const T& in, std::true_type)
{
    // T is a std::complex, do scaling
    const typename T::value_type theta = M_PI/2.0;
    const T y(std::cos(theta),-1*std::sin(theta));
    out = out*y;
}

template<typename T>
void myFunction(T& out, const T& in)
{
    out = in;
    myFunction_impl(out, in, is_complex<T>{});
}

Demo

请注意,直接重载不起作用,因为 std::complex<T>参数将被解析为 std::complex<std::complex<T>>在尝试选择正确的过载时。

关于c++ - 仅当类型为 std::complex 时才缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62201557/

相关文章:

python - 具有不明确标识符的空指针

c++ - 调用 const 成员函数

c++ - 可变参数模板索引包扩展

C++模板T,检测Type为字符串形式

c++ - enable_if 模板参数是 lambda(具有特定签名)

c++ - 一个函数将 *this 列表与另一个列表连接起来,并将结果列表存储在新列表中。避免内存泄漏

c++ - "invalid cast from type ' const myClass ' to type ' int '",我怎样才能让它有效?

C++ 类型标识符

c++ - 条件变量 "miss"可以通知调用吗?

c++ - 模板文件中的类 'does not name a type' 错误