[英]Default value for template parameter, followed by non-type parameter pack
我正在努力使這段代碼工作
template <typename T, typename U = int, auto... Params>
class Foo {};
int main()
{
auto foo1 = Foo<int, int, 1, 2, 3>{};
auto foo2 = Foo<int, 1, 2, 3>{}; // I want it to compile
}
看來我需要一些技巧。 我嘗試了部分專業化,但它也不起作用
template <typename T, typename U, auto... Params>
class Foo {};
template <typename T, auto... Params>
class Foo<T, int, Params...> {};
int main()
{
auto foo1 = Foo<int, int, 1, 2, 3>{};
auto foo2 = Foo<int, 1, 2, 3>{}; // I want it to compile
}
我找不到與此密切相關的任何內容,請幫助:)
不幸的是,由於模板推導的工作方式,這……行不通。
這是另一種方法,其中第一個模板參數始終是一個元組,具有一種或兩種類型,第二種類型默認為int
:
#include <tuple>
template<typename T, auto ...Params> class Foo;
template<typename T, typename U, auto ...Params>
class Foo< std::tuple<T, U>, Params...> {
// Your template goes here, making use of T and U
};
template<typename T, auto ...Params>
class Foo< std::tuple<T>, Params...> : Foo<std::tuple<T, int>, Params...> {
// Might need to define some cleanups here, like a delegating constructor,
// and/or delegated overload operators.
};
Foo<std::tuple<char>, 3, 4> defaulted;
Foo<std::tuple<char, float>, 3, 4> non_defaulted;
稍微麻煩一點,只有在需要指定第二個可選類型時才需要正式的std::tuple
,並且只需直接指定主要類型(盡管如果主要類型是,這將產生一些可避免的混淆一個std::tuple
本身)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.