我想將要傳遞給模板函式的物件變數串列作為一系列大括號括起來的初始化程式傳遞。
所以是這樣的:
enum class E { a, b, c };
template <typename T>
struct Info
{
template <typename U>
Info(E e, U u)
: e(e)
, size(sizeof(u))
{}
E e;
size_t size;
};
template <typename...Ts>
void fn(Info<Ts>&&...args) { }
int f() {
fn({ E::a, 5 });
}
如果我用具體型別替換上面的內容,括號括起來的初始化程式確實有效:
enum class E { a, b, c };
struct InfoBase { E e; int size; };
void f1(InfoBase&& a, InfoBase&& b) { }
void f() {
f1({ E::a, 4 }, { E::b, 6 });
}
但替換f1為以下失敗:
void f1() { }
template <typename...Ts>
void f1(InfoBase&& a, Ts&&...args)
{
f1(std::forward<Ts>(args)...);
}
大概是因為它無法推斷Ts?
錯誤訊息是:
<source>: In function 'void f()':
<source>:22:7: error: no matching function for call to 'f1(<brace-enclosed initializer list>, <brace-enclosed initializer list>)'
22 | f1( { E::a, 4 }, { E::b, 6 } );
| ~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:16:6: note: candidate: 'void f1(InfoBase&&, Ts&& ...) [with Ts = {}]'
16 | void f1(InfoBase&& a, Ts&&...args) {
| ^~
<source>:16:6: note: candidate expects 1 argument, 2 provided
<source>:14:6: note: candidate: 'void f1()'
14 | void f1() { }
| ^~
<source>:14:6: note: candidate expects 0 arguments, 2 provided
我想是因為Ts沒有要系結的具體型別,它只是失敗了,即使該資訊稍后在呼叫樹中可用。那是對的嗎?
我正在嘗試的事情是不可能的嗎?
uj5u.com熱心網友回復:
由于plain {}, 沒有型別,所以不能用于模板型別推導。
據我了解,您正在努力實作,我提出以下建議
template <typename T, typename...Ts>
void fn(E e, T&& val, Ts&&...args)
{
Info<T> ob{ e, std::forward<T>(val) }; // do something with ob
// ....
if constexpr (sizeof...(args) == 1u) {
std::cout << "At least required two args!\n";
// other error msgs or handling
}
else if constexpr (sizeof...(args)) {
fn(std::forward<Ts>(args)...); // process what left by recursive calls
}
}
現在傳遞/呼叫函式為
fn(E::a, 4, E::b, 6);
在 godbolt.org 中查看演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521302.html
上一篇:前向宣告模板型別引數
