【问题标题】:Deduce datatype based on the input datatype in C++根据 C++ 中的输入数据类型推断数据类型
【发布时间】:2021-12-04 17:11:22
【问题描述】:

有没有办法在 C++ 中从输入推导出函数的数据类型?

例子:

template<typename T>
func(T input){
    if((std::is_same<T, float>::value))
        uint32_t compute;
    else if((std::is_same<T, double>::value))
        uint64_t compute;

    // rest of the function which uses compute value to do necessary computation.
}

我理解当前的声明,变量的范围在if 条件循环之后消失。所以我添加了一个func_compute 并从每个if 条件中调用它。

我想知道,有没有更清洁的方法?

【问题讨论】:

    标签: c++ c++11 c++14


    【解决方案1】:

    你可以使用std::conditional:

    #include <iostream>
    #include <type_traits>
    #include <cstdint>
    
    template <typename T>
    void func(T input)
    {
        typename std::conditional<
            std::is_same<T, float>::value,
            std::uint32_t,
            typename std::conditional<
                std::is_same<T, double>::value,
                std::uint64_t,
                void
            >::type
        >::type compute;
        std::cout << sizeof compute << '\n';
    }
    
    int main(void)
    {
        func(1.23);
        func(1.23f);
    //  func(1); // error: variable or field 'compute' declared void
    }
    

    可能的输出:

    8
    4
    

    【讨论】:

    • 或者,在 C++14 及更高版本中,std::conditional_tstd::is_same_v,这将进一步清理该声明
    • @RemyLebeau 是的,你是对的,而且它们使用起来肯定更干净,但不幸的是,std::is_same_v 直到 C++17 才出现:/ OP 将他们的问题标记为 [ c++14] 和 [c++11] 所以他们可以使用 std::conditional_t 假设 C++14 但我决定让它也与 C++11 兼容。
    【解决方案2】:

    C++17 的constexpr if 非常适合你的情况。如果你不介意使用 C++17(尽管我强烈怀疑),还有一种更简洁的方法:

    #include <type_traits>
    #include <cstdint>
    
    template<typename T> 
    void func(T input){
      auto compute = [] {
        if constexpr (std::is_same_v<T, float>)
          return std::uint32_t{};
        else if constexpr (std::is_same_v<T, double>)
          return std::uint64_t{};
      }();
    
      // rest of the function which uses compute value to do necessary computation.
    }
    

    Demo.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      • 2022-01-05
      相关资源
      最近更新 更多