簡體   English   中英

根據 C++ 中的輸入數據類型推斷數據類型

[英]Deduce datatype based on the input datatype in C++

有沒有辦法從 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條件調用它。

我想知道,有沒有辦法以更清潔的方式做到這一點?

您可以使用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++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.
}

演示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM