成员函数模板不会在 clang 上编译,但在 GCC 上编译
Member function template doesn't compile on clang, but does on GCC
在下面的代码中,我有一个名为 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()
的非成员函数模板调用相同的代码(与 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>();
}
使用如下所示的模板成员函数时,需要使用 template 关键字:
my_postoffice.template get_postbox<K>()
和
po.template get_postbox<D>()
c.f. 在这里:代码的 http://ideone.com/W0owY1在这里:我必须在哪里以及为什么必须放置"模板"和"类型名称"关键字?有关何时使用模板关键字的确切说明
相关文章:
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- 编译在我的 Mac 上工作,但在集群 (Linux) 上不起作用
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 在Visual Studio中使用括号时编译错误,但在G ++ / CLang ++中传递
- std::to_chars在MacOS/clang上编译但不链接
- 带有引用的std::tuple在clang中编译失败,但在gcc中编译失败
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 我有一个C++函数,它在Dev C++中编译,但在G++中不编译
- Lua :在原生lua中编译,但在使用LuaJIT和sol2时C++出错
- 分配给静态变量的局部变量;编译错误在'c'但在 C++ 中成功
- 运行程序时找不到共享对象库,但在编译过程中链接了它
- C++代码编译,但在 Zorin OS 上运行时显示错误
- 我正在尝试使用回溯来解决 N queen 问题,但在编译时它会给出运行时错误(动态堆栈缓冲区溢出)
- Cmake Mac OSX库链接问题:在Linux上进行编译,但在Mac上进行了编译
- cmake cuda在Windows上单独的编译静态LIB链接错误,但在Ubuntu上没有
- strcpy 在 Windows 上编译,但在 Linux 上不编译
- 在 Windows 上编译错误 C2131 和 C3863,但在 Linux 上不编译错误
- 相同的代码在 Dev C++ 上编译,但在 Visual Studio 2017 上不编译
- 从std::map派生的类不在Visual C++上编译(但在gcc和clang上编译)
- 在 Xcode 6 中运行 cpp-netlib - 编译但在运行时崩溃