我不明白為什么下面這個簡單的例子失敗了:
#include <boost/hana.hpp>
template <typename _T>
static constexpr void Foo(boost::hana::type<_T>) {
}
int main() {
Foo(boost::hana::type_c<int>);
return 0;
}
我收到以下錯誤訊息:
[build] error: no matching function for call to ‘Foo(boost::hana::type<int>&)’
[build] 74 | Foo(hana::type_c<int>);
[build] | ~~~^~~~~~~~~~~~~~~~~~~
[build] note: candidate: ‘template<class _T> constexpr void Morphy::Foo(boost::hana::type<T>)’
[build] 61 | static constexpr void Foo(hana::type<_T>) {
[build] | ^~~
[build] note: template argument deduction/substitution failed:
[build] note: couldn’t deduce template parameter ‘_T’
[build] 74 | Foo(hana::type_c<int>);
[build] | ~~~^~~~~~~~~~~~~~~~~~~
使上述作業的唯一方法是Foo通過撰寫明確的模板引數Foo<int>(boost::hana::type_c<int>)。為什么編譯器無法自動推匯出模板引數?
請注意,上面的代碼作業,如果我使用boost::hana::basic_type的地方boost::hana::type在申報Foo。這種替代方法是否正確?
uj5u.com熱心網友回復:
type_c<int>是一個創建型別值的變數模板type<int>。確實看起來Foo應該很容易_T從type<_T>傳遞時推斷出引數type<int>。然而這是不可能的,因為它是type一個別名模板,它參考了某個輔助類的成員,并且它的引數總是在非推導的背景關系中。
template< typename x_Type >
struct FooImpl
{
using Type = x_Type;
};
template< typename x_Type >
using Foo = typename FooImpl<x_Type>::Type;
template< typename x_Type > // x_Type can not be deduced
void Bar(Foo<x_Type>) {}
int main()
{
Bar(Foo<int>{});
return 0;
}
在線編譯器
basic_type有效,因為它是type_c.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380314.html
下一篇:回傳型別取決于模板引數型別
