簡體   English   中英

為可變參數模板中給定的所有類型添加模板特化

[英]Adding template specialization for all types given in variadic template

我在模板上有大量的作業,其中一部分是創建結構template <typename... Types> struct Foo ,其中包含一個公共結構template<typename Type> struct Bar ,它共享(在公共type定義中)一個結構其中必須包含一個公共方法template<typename Type> static constexpr size_t count(); 如果在FooBar參數中指定了類型,則輸出1否則輸出0 示例(以下代碼應編譯):

using FooBar = Foo<foo1,foo2,foo3>;

using Foo1Type = FooBar::Bar<foo1>::type;
// foo1 was given as argument to Foo and Bar
static_assert(Foo1Type::count<foo1>() == 1);
// foo2 was given as argument to Foo, but not Bar
static_assert(Foo1Type::count<foo2>() == 0);

using Foo4Type = FooBar::Bar<foo4>::type;
// foo4 was not given as argument to Foo
static_assert(Foo4Type::count<foo4>() == 0); 
static_assert(Foo4Type::count<foo1>() == 0);

在我看來,它似乎很頑固(我是模板的新手,剛剛開始閱讀它們),似乎我們必須遍歷各種模板參數到Foo ,並在迭代過程中以某種方式為內部結構Bar創建新的專業化知識……從來沒有見過這樣的事情,所以我只能猜測如何做到。

那么,我是否在以很好的方式思考此問題,還是應該以某種不同的方式來解決它? 感謝您提供的幫助(不僅僅是完整的解決方案)-歡迎使用任何有用的鏈接。

據我了解,您的內部功能就像這樣:

return contain<Type, TBar>{} && contain<Type, TFoos...>{};

該結構包含可以寫成:

template <typename T, typename ... Ts> struct contain;

// Partial specializations
// Empty case
template <typename T> struct contain<T> : std::false_type {};

// Found
template <typename T, typename ... Tail>
struct contain<T, T, Tail...> : std::true_type {};

// Not found, iterate the list
template <typename T, typename Head, typename ... Tail>
struct contain<T, Head, Tail...> : contain<T, Tail...> {};

演示

暫無
暫無

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

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