當我上課時:
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)
uj5u.com熱心網友回復:
如果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');
}
現場演示
uj5u.com熱心網友回復:
為什么以及如何解決這個問題?
問題是當使用類模板引數推導(又名 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),因此似乎不需要額外的 type 非型別模板引數size_t。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/486486.html
