我有一個使用宣告的嵌套模板鏈。它看起來像這樣:
template <typename A, typename B, typename C, typename D>
class Foo {
public:
Foo() : value{0} {};
template <typename AC, typename BC, typename CC, typename DC>
Foo(const Foo<AC, BC, CC, DC>& rhs) : value{rhs.value} {}
template <typename AC, typename BC, typename CC, typename DC>
Foo& operator=(const Foo<AC, BC, CC, DC>& rhs) {
value = rhs.value;
return *this;
}
template <typename F>
F convertTo() {
return F(*this);
}
C value;
};
template <typename ThingC, typename ThingD>
using Bar = Foo<int, float, ThingC, ThingD>;
template <typename ThingD = long double>
using Bif = Bar<char, ThingD>;
以下給我帶來了麻煩:
int main(int argc, char* argv[]) {
Bif bifDefault;
Bif<long> bifLong;
Bif<unsigned> bifUnsigned = bifDefault.convertTo<Bif<unsigned>>();
Bif<long double> bifLongDouble = bifLong.convertTo<Bif>(); // ERROR...
// expected a type, got 'Bif'
}
我也收到一條錯誤F convertTo訊息:template argument deduction/substitution failed。
還有最奇怪的錯誤,在 ERROR 行:
no instance of function template "Foo<A, B, C, D>::convertTo [ with A=int, B=float, C=char, D=long int]" matches the argument list
D=長整數!這里發生了什么?將其更改為 double 也不起作用。顯然,默認模板引數正在傳播到函式,但它在long double 中做錯了,即使它確實獲得了正確的型別也不起作用。
我怎樣才能讓它作業?
uj5u.com熱心網友回復:
問題是這Bif不是型別,而是templated 型別。bifDefault由于CTAD宣告時,您將僥幸逃脫,但在您呼叫時它并不適用convertTo(您沒有傳遞非型別template引數)。替換為 時,代碼按預期編譯bifLong.convertTo<Bif<>>()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/486494.html
上一篇:C 函式模板實參推導指南
