給定一個類的形式:
template <int A, int B, int C>
struct Functor {
static int go() {
return A*B*C;
}
};
我需要為 Functor生成引數型別的引數包/元組/等。也就是說,我希望能夠執行以下操作:
// Imagining that I have many Functor classes...
using FirstArgType = TypeAt<Functor, 1>::T;
FirstArgType t {4};
本質上,我需要從值的引數包,到非專業模板類的那些值的 TYPES 的引數包- 即,Functor而不是Functor<1, 2, 3>. 我天真地從看起來像這樣的事情開始:
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>)以找出型別 - 但我試圖對模板類Functor進行操作,而不是它的專業化Functor<n,n,n>- 我需要用于對每個專業化進行操作的模板代碼,例如Functor<1, 2, 3>和Functor<4, 5, 6>,而不僅僅是查找特定專業化的型別。
一方面:我覺得我正在嘗試使用 C 模板根本不可能的事情——以我不理解的方式——這就是為什么我能想到的每個公式都失敗了。
另一方面:顯然模板引數的型別Functor在編譯時是眾所周知的,所以我想應該有一種方法可以發現這些。
一個解決方案會很棒,但我同樣很高興聽到有關處理我不熟悉的模板模板引數的策略/技術/設計模式(我不會認為自己是這里的專業人士)。
uj5u.com熱心網友回復:
本質上,我需要從值的引數包到這些值的 TYPES 的引數包。
您可以使用模板部分特化來提取非型別模板引數的型別,如下所示:
#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>>);
演示。
uj5u.com熱心網友回復:
你的意思是這樣的嗎?
#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 };
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388430.html
上一篇:匯出需要標準概念的模板函式
