在下面的代码中,我有一个名为zipcode
的类模板,它有一个名为get_postbox
的成员函数模板。它在 GCC 中编译但不在 clang 3.9 中编译。为什么 clang 不接受这个代码?
在 clang 中我得到这个错误:
<source>:34:41: error: expected expression
return my_postoffice.get_postbox<K>();
^
此外,从名为 non_member_function_template()
的 non-member 函数模板调用相同的代码(与 zipcode::get_postbox
相同)不会导致错误!
要亲自查看并使用它,这里是 Compiler Explorer 中的代码: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>();
}
最佳答案
像这样使用模板成员函数时需要使用模板关键字:
my_postoffice.template get_postbox<K>()
和
po.template get_postbox<D>()
比较这里:http://ideone.com/W0owY1对于代码 在这里:Where and why do I have to put the "template" and "typename" keywords?有关何时使用模板关键字的确切说明
关于c++ - 成员函数模板不在 clang 上编译,但在 GCC 上编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41875820/