【发布时间】:2017-01-26 14:34:14
【问题描述】:
在下面的代码中,我有一个名为zipcode 的类模板,它有一个名为get_postbox 的成员函数模板。它可以在 GCC 中编译,但不能在 clang 3.9 中编译。为什么 clang 不接受这个代码?
在铿锵声中我得到这个错误:
<source>:34:41: error: expected expression
return my_postoffice.get_postbox<K>();
^
此外,从名为non_member_function_template() 的非成员 函数模板调用相同的代码(与zipcode::get_postbox 相同)不会导致错误!
要亲自查看并使用它,这是编译器资源管理器中的代码: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>();
}
【问题讨论】:
-
你需要
return my_postoffice.template get_postbox<K>();。 -
@songyuanyao 不错!那行得通。谢谢!
-
查看更多详情here。