簡體   English   中英

在編譯時選擇一個變量

[英]Select a variable at compile-time

我希望能夠通過布爾指定我需要在編譯時使用哪兩個變量,所有這些都沒有直接的SFINAE 只有一個函數,類似於std::conditional但不返回類型。

因此,例如在課堂test ,我想擁有

class test
{
    template <class T, bool first, MAGIC_HAPPENS var>
    void apply_it(T &t)
    {
        for (auto &p : var) p.apply(t);
    }

    std::vector<myfunction> var1;
    std::vector<myfunction> var2;
}

使用很簡單:如果我指定first == true那么它應該應用var == var1的循環,否則var == var2

可能嗎?

只是為了好玩(*),對當前代碼片段的最小 C ++ 17(**)修改可能是

class test
{
    std::vector<myfunction> var1;
    std::vector<myfunction> var2;

    template <class T, bool first, std::vector<myfunction> test::*var = first ? &test::var1 : &test::var2 >
    void apply_it(T &t)
    {
        for (auto &p : this->*var) p.apply(t);
    }
};

(*)我認為沒有哪種情況比其他建議的解決方案更可取...

(**)據我所知,由於模板非類型指針參數的鏈接要求,這需要C ++ 17 ...

對於C ++ 17及以上版本:

class test
{
    template <class T, bool first>
    void apply_it(T &t)
    {
        if constexpr (first)
        {
            for (auto &p : var1) p.apply(t);
        }
        else
        {
            for (auto &p : var2) p.apply(t);
        }
    }

    std::vector<myfunction> var1;
    std::vector<myfunction> var2;
}

if constexpr在編譯時被評估,如果條件是constexpr,則模板參數就是這種情況。

您可以在C ++ 11中使用指向數據成員的指針執行此操作:

class test
{
    template <class T, bool first>
    void apply_it(T &t)
    {
        constexpr auto var = first ? &test::var1 : &test::var2;
        for (auto &p : this->*var) p.apply(t);
    }

    std::vector<myfunction> var1;
    std::vector<myfunction> var2;
}
template<std::size_t I, class...Args>
decltype(auto) pick( Args&&... args ) {
  return std::get<I>( std::forward_as_tuple( std::forward<Args>(args)... ) );
}

pick在編譯時從列表中選擇一些東西。

class test
{
  template <bool first, class T>
  void apply_it(T&& t)
  {
    auto&& var = pick<first?0:1>(var1, var2);
    for (auto&& p : var)
      p.apply(t);
  }

  std::vector<myfunction> var1;
  std::vector<myfunction> var2;
};

我復制粘貼時也做了一些小的改進。

暫無
暫無

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

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