簡體   English   中英

根據模板 class 查找非類型模板參數的類型

[英]Find the type of a non-type template parameter, based on a template class

給定一個 class 的形式:

template <int A, int B, int C>
struct Functor {
  static int go() {
    return A*B*C;
  }
};

我需要為 Functor 生成參數類型的參數包/元組/等。 也就是說,我希望能夠執行以下操作:

// Imagining that I have many SomeFunctor classes...
using FirstArgType = TypeAt<SomeFunctor, 1>::T;
FirstArgType t {4};

本質上,我需要 go 從值的參數包到這些值的類型的參數包。 我天真地從看起來像這樣的事情開始:

template <template <auto...Values> typename Class>
struct ClassInfo {
   using Tuple = std::tuple<decltype(Values)...>;
};

但是,嵌套的模板模板參數不能像這樣訪問( error: use of undeclared identifier 'Values' )。 請注意,當我使用auto...Values作為頂級模板參數時,這種元組技術可以很好地發現類型 - 問題在於提取Class的模板參數。

對於我嘗試過的非常公式,我需要在某些時候指定一個具體類型(例如Functor<1, 2, 3> )以找出類型 - 但是,我失去了一般提供任何模板化 class 的能力並推斷它需要的類型。

一方面:我覺得我正在嘗試用 C++ 模板做一些根本不可能的事情——以我不理解的方式——這就是為什么我能想到的每個公式都失敗了。

另一方面:很明顯Functor的模板參數的類型在編譯時是眾所周知的,所以我想應該有一種方法來發現這些。

一個解決方案會很棒,但我同樣很高興聽到有關處理我不熟悉的模板-模板參數的策略/技術/設計模式(我不認為自己在這里是專業人士)。

本質上,我需要 go 從值的參數包到這些值的類型的參數包。

您可以使用模板偏特化來提取非類型模板參數的類型,如下所示:

#include <tuple>

template<auto... args>
struct Functor {};

template <class>
struct ClassInfo {};

template <auto... args>
struct ClassInfo<Functor<args...>> {
  using type = std::tuple<decltype(args)...>;
};

using F = Functor<0, 42u, 'a', true>;
static_assert(
  std::is_same_v<ClassInfo<F>::type, std::tuple<int, unsigned, char, bool>>);

演示。

你的意思是這樣的嗎?

#include <tuple>

template <auto... Values>
struct GenericFunctor {
    using Tuple = std::tuple<decltype(Values)...>;
};

using SpecificFunctor = GenericFunctor<short(1), long(2)>;

// Extracts specific template types from functors.
template<class Functor, int i>
using ArgType = decltype(std::get<i>( std::declval<typename Functor::Tuple>() ));

// Instantiate the specific arg type.
static ArgType<SpecificFunctor, 1> t { 1 };

暫無
暫無

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

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