为什么SFINAE导致编译器错误,它应该工作
Why SFINAE results in compiler error where it should have worked?
我试图实现一个元程序,发现如果给定的指针类型是const
或不。例如
-
is_const<TYPE*>::value
应该是false
-
is_const<const TYPE*>::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()
)。我很想知道这里出了什么问题。
为什么这么兜圈子?那么直接的trait类呢:
#include <functional>
template <typename T> struct is_const_ptr : std::false_type { };
template <typename T> struct is_const_ptr<const T *> : std::true_type { };
struct Foo {};
int main()
{
std::cout << is_const_ptr<Foo*>::value << is_const_ptr<const Foo*>::value << std::endl;
}
你的问题是:
static yes& check (const T*&);
static char check (T*&);
当您实例化is_const<int*>
时,您的函数定义扩展为:
static yes& check (const int**&);
static char check (int**&);
但是,您的临时项(TYPE it
)的类型是int*
,就像您指定的那样。您需要更改check
函数签名以删除指针说明符,如下所示:
static yes& check (const T&);
static char check (T&);
你的代码有两处错误。
首先,下面的
static yes& check (const T*&);
static char check (T*&);
必须改为
static yes& check (const T&);
static char check (T&);
其次,it
成员必须是static
static TYPE it;
或者,将((TYPE)0)
传递给检查函数。不需要成员
相关文章:
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 这些是什么样的错误?即使我不在 Linux 上工作,我也遇到了 Linux 错误
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 实现 DFS 在较短的输入下工作正常,但在较大的输入下会抛出分段错误
- C++代码停止工作错误使用cout内部函数
- 我的代码无法正常工作。谁能指出错误?
- 请发现它在 dev 中工作的错误,但在 hackerrank 中不起作用
- 错误:三元运算符无法在对象中正常工作"cout"
- 一个非常简单的win32套接字代码,但工作错误
- 如何组织 git 工作流以修复错误并同时引入新功能
- emplace_back初始化列表错误,当初始化列表在独立变量上工作时
- 在调试配置中编译工作正常,但发布会给出链接错误
- .exe应用程序在windows10中创建新模块时抛出错误,但在windows7中工作正常
- 我的随机生成器是否不工作,或者我决定人/骨架是否击中对手的方式是否有错误
- 代码作为 C 文件工作,但不作为C++文件,错误:'__builtin_types_compatible_p'未在此范围内声明
- 当代码在Visual Studio C++中正常工作时,MSB6006错误
- 错误太多参数无法正常工作
- 为什么我必须将错误状态标志设置为 goodbit 才能使其工作
- 我的va_start/va_end宏工作错误
- 代码中没有错误,但是当我运行程序时,我得到“多项式.exe已停止工作”.错误