为什么 SFINAE 会在它应该起作用的地方导致编译器错误?
我试图实现一个元程序,它可以查找给定的指针类型是否为 const 。即
is_const
应该是::value false
is_const
应该是::value true
以下是代码:
template<class TYPE>
struct is_const
{
typedef char yes[3];
template<typename T>
struct Perform
{
static yes& check (const T*&);
static char check (T*&);
};
TYPE it;
enum { value = (sizeof(Perform<TYPE>::check(it)) == sizeof(yes)) };
};
编译器错误消息是:
In instantiation of ‘is_const<int*>’:
instantiated from here
error: no matching function for call to ‘is_const<int*>::Perform<int*>::check(int*&)’
note: candidates are: static char (& is_const<TYPE>::Perform<T>::check(const T*&))[3] [with T = int*, TYPE = int*]
note: static char is_const<TYPE>::Perform<T>::check(T*&) [with T = int*, TYPE = int*]
我的焦点已转移到错误消息。如果您看到最后一行:
note: static char is_const<TYPE>::Perform<T>::check(T*&) [with T = int*, TYPE = int*]
如果我们真的替换 T = int*
和 TYPE = int*
那么它确实应该匹配适当的函数 (char check() )。我很想知道这里出了什么问题。
I was trying to implement a meta-program which finds if given pointer type is const
or not. i.e.
is_const<TYPE*>::value
should befalse
is_const<const TYPE*>::value
should betrue
Following is the code:
template<class TYPE>
struct is_const
{
typedef char yes[3];
template<typename T>
struct Perform
{
static yes& check (const T*&);
static char check (T*&);
};
TYPE it;
enum { value = (sizeof(Perform<TYPE>::check(it)) == sizeof(yes)) };
};
And the compiler error messages are:
In instantiation of ‘is_const<int*>’:
instantiated from here
error: no matching function for call to ‘is_const<int*>::Perform<int*>::check(int*&)’
note: candidates are: static char (& is_const<TYPE>::Perform<T>::check(const T*&))[3] [with T = int*, TYPE = int*]
note: static char is_const<TYPE>::Perform<T>::check(T*&) [with T = int*, TYPE = int*]
My focus has shifted to the error message. If you see the last line:
note: static char is_const<TYPE>::Perform<T>::check(T*&) [with T = int*, TYPE = int*]
If we really replace T = int*
and TYPE = int*
then it really should match the appropriate function (char check()
). I am anxious to know that what is going wrong here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为何如此迂回?一个简单的特征类怎么样:
Why so roundabout? How about a straight-forward trait class:
这是您的问题:
当您实例化
is_const
时,您的函数定义将扩展为:但是,您的临时项 (
TYPE it
) 的类型为int*
,就像您指定的那样。您需要更改check
函数签名以删除指针说明符,如下所示:Here's your problem:
When you instantiate
is_const<int*>
, your function definitions are expanded to:However, your temporary item (
TYPE it
) is of typeint*
, like you specified. You need to change yourcheck
function signatures to remove the pointer specifier, like so:您的代码中有两处错误。
首先,以下内容
必须更改为
Ans 其次,
it
成员必须是static
,或者只需将
((TYPE)0)
传递给您的检查功能。不需要会员。THere are two things wrong in your code.
First, the following
must be changed to
Ans second, the
it
member must bestatic
or, just pass
((TYPE)0)
to your check function. No need of the member.