如何解决SFINAE 外部实现的 g++ 和 clang++ 不同的行为
关于 C++ 语言层的另一个问题。
使用以下代码,我尝试启用方法 foo<T>::bar()
,仅当 T
是常量类型并使用 using
中定义的 foo<T>
别名类型时,实现它(启用时)在类/结构体之外。
#include <type_traits>
template <typename T>
struct foo
{
using cT = T const;
template <typename U = T,std::enable_if_t<std::is_same_v<U,cT>,int> = 0>
void bar ();
};
template <typename T>
template <typename U,typename foo<T>::cT>,int>>
void foo<T>::bar () // ......................^^^^^^^^^^^^^^^^^^^
{ } // wrong for g++
int main()
{
}
此代码在使用 clang++(例如 HEAD 13.0.0,但也有较旧版本)时没有问题,但是使用 g++(例如 HEAD 12.0.0,但也有较旧版本)会出现以下编译错误
prog.cc:16:6: error: no declaration matches 'void foo<T>::bar()'
16 | void foo<T>::bar ()
| ^~~~~~
prog.cc:10:9: note: candidate is: 'template<class T> template<class U,typename std::enable_if<is_same_v<U,const T>,int>::type <anonymous> > void foo<T>::bar()'
10 | void bar ();
| ^~~
prog.cc:4:8: note: 'struct foo<T>' defined here
4 | struct foo
| ^~~
问题似乎是在外部实现中使用了 typename foo<T>::cT
,对于 clang++ 匹配内部声明中相应的 cT
,对于 g++ 不匹配。
如果直接使用T const
,在外部实现中,
template <typename T>
template <typename U,T const>,int>>
void foo<T>::bar () // ......................^^^^^^^
{ } // now compile with both g++ and clang++
和往常一样,问题是:谁是对的? g++ 还是 clang++?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。