[英]variadic template deduction with two template argument fails
當我上課時:
template <std::same_as<char> ... Indices>
struct MIndices {
std::tuple<Indices...> indices;
MIndices() = delete;
constexpr explicit MIndices(Indices... args) : indices(args...) {
}
};
以下調用有效:
MIndices myI('i', 'j', 'l', 'z');
但是將模板更改為以下內容:
template <size_t Dims, std::same_as<char> ... Indices>
struct MIndices {
std::tuple<Indices...> indices;
MIndices() = delete;
constexpr explicit MIndices(Indices... args) : indices(args...) {
}
};
然后用
MIndices<4> myI('i', 'j', 'l', 'z');
突然無法推斷出論點。
為什么以及如何解決這個問題?
所以原則上我只想有一種編譯時的方式來指定元組參數的數量。 如果這是一個不好的方法,請告訴我。
我正在使用 c++20。 (GCC-12.1)
為什么以及如何解決這個問題?
問題是當使用類模板參數推導(又名 CTAD)時,所有模板參數必須由推導過程或默認參數確定。 不可能明確指定幾個參數並推導出其他參數。
因此,要解決這個問題,您必須明確指定所有模板參數或推導出所有參數。 所以解決這個問題的一種方法是:
MIndices<4, char, char, char, char> myI('i', 'j', 'l', 'z');
也許一個更簡化的例子可能有助於說明這一點:
template<typename T1, typename T2, typename T3>
class Custom
{
public:
Custom (T1 x, T2 y, T3 z)
{
}
};
int main()
{
std::string s;
Custom c(3, 2.343, s); //works
//Custom<int> b(4, 2,343, s); //WON'T WORK
Custom<int, int, std::string> k(4, 4, "s"); //works
}
如果這是一個不好的方法,請告訴我。
您可以選擇使用sizeof...(Indices)
因此似乎不需要額外的size_t
類型的非類型模板參數。
如果Dims
應該等於傳遞的參數數量,則應該使用sizeof...
運算符,而不是讓調用者指定大小。
CTAD(類模板參數推導)僅在推導類的所有模板參數時才有效。
解決方法是推導出所有參數。 您可以將推斷索引的類包裝到另一個可以明確給出大小的類中:
#include <iostream>
#include <tuple>
template <size_t Dims>
struct wrapper {
template <std::same_as<char> ... Indices>
struct MIndices {
std::tuple<Indices...> indices;
MIndices() = delete;
constexpr explicit MIndices(Indices... args) : indices(args...) {
}
};
};
int main() {
wrapper<4>::MIndices myI('i', 'j', 'l', 'z');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.