![](/img/trans.png)
[英]Why this template constexpr function doesn't compile on gcc but works well on clang?
[英]Member function template doesn't compile on clang, but does on GCC
在下面的代碼中,我有一個名為zipcode
的類模板,其中有一個名為get_postbox
的成員函數模板。 它在GCC中編譯,但在clang 3.9中不編譯。 為什么clang不接受此代碼?
在c我得到這個錯誤:
<source>:34:41: error: expected expression
return my_postoffice.get_postbox<K>();
^
此外,從名為non_member_function_template()
的非成員函數模板調用相同的代碼(與zipcode::get_postbox
相同non_member_function_template()
不會導致該錯誤!
要親自查看並使用它,請參見以下編譯器資源管理器中的代碼: https : //godbolt.org/g/MpYzGP
這是代碼:
template <int K>
struct postbox
{
int val() const
{
return K;
}
};
template <int A, int B, int C>
struct postoffice
{
postbox<A> _a;
template<int I>
postbox<I> get_postbox()
{
switch( I )
{
case A: return _a;
}
}
};
template <typename PO>
struct zipcode
{
PO my_postoffice;
template<int K>
postbox<K> get_postbox()
{
// The error is on this line
return my_postoffice.get_postbox<K>();
}
};
// Here's a function template that isn't a member, and it compiles.
template<int D>
int non_member_function_template()
{
postoffice<123,345,678> po;
auto box = po.get_postbox<D>();
return box.val();
}
int test_main()
{
return non_member_function_template<123>();
}
使用這樣的模板成員函數時,需要使用template關鍵字:
my_postoffice.template get_postbox<K>()
和
po.template get_postbox<D>()
參見此處: http : //ideone.com/W0owY1以獲取代碼,以及以下位置: 為什么在何處以及為什么必須放置“模板”和“類型名”關鍵字? 有關何時使用template關鍵字的確切說明
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.