【问题标题】:Apply std::conj in template function if template argument is complex如果模板参数很复杂,则在模板函数中应用 std::conj
【发布时间】:2020-08-08 22:18:18
【问题描述】:

TL;DR 假设我有一个带有模板参数 T 的函数,它接受 std::vector<T>& 作为输入(见下文),如果 T是一个复杂的类型。我该怎么做?

我的尝试https://stackoverflow.com/a/30737105/5913047之后,我知道我可以检查一个类型是否复杂

template<class T> struct is_complex : std::false_type {};
template<class T> struct is_complex<std::complex<T>> : std::true_type {};

所以我尝试了:

template<typename T>
void MyFunction(std::vector<T>& MyVector){
    // do something
    if (is_complex<T>()){
       std::transform(MyVector.begin(), MyVector.end(), MyVector.begin(),[](T&c){return std::conj(c););
    }
}

但是,如果我将此函数用于非复杂类型,编译器会说conj 没有为非复杂类型定义。有什么设计可以做我想做的吗?

【问题讨论】:

    标签: c++ c++11 complex-numbers


    【解决方案1】:

    您正在使用if 语句。这要求if 分支中的代码是可编译的,即使您不需要执行它也是如此。

    在c++17中,要有条件地编译一段代码,你可以像这样使用if constexpr

    if constexpr (is_complex<T>()) {
     //^^^^^^^^^   
        std::transform(MyVector.begin(), MyVector.end(), MyVector.begin(),[](T&c){ return std::conj(c); });
    }
    

    这是demo

    在c++11中,可以使用std::enable_if为类型不复杂的情况编写重载,像这样:

    template<typename T, typename std::enable_if<!is_complex<T>::value, int>::type = 0>
    void MyFunction(std::vector<T>& MyVector){
        // do something
    }
    
    template<typename T,  typename std::enable_if<is_complex<T>::value, int>::type = 0>
    void MyFunction(std::vector<T>& MyVector){
        // do something
        std::transform(MyVector.begin(), MyVector.end(), MyVector.begin(),[](T&c){ return std::conj(c); });
    }
    

    这是demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多