do decltype 需要一个涉及完整类型的表达式
do decltype needs an expression involving complete type?
请考虑以下代码,该代码尝试确定嵌套 typedef 的存在。
#include<type_traits>
struct foo;// incomplete type
template<class T>
struct seq
{
using value_type = T;
};
struct no_type{};
template<class T>
struct check_type : std::true_type{};
template<>
struct check_type<no_type> :std::false_type{};
template<class T>
struct has_value_type
{
template<class U>
static auto check(U const&)-> typename U:: value_type;
static auto check(...)->no_type;
static bool const value = check_type<decltype(check(std::declval<T>()))>::value;
using type = has_value_type;
};
int main()
{
char c[has_value_type<seq<foo>>::value?1:-1];
(void)c;
}
现在调用has_value_type<seq>::value
会导致编译错误,因为无效使用不完整的类型seq<foo>::value_type
。decltype
是否需要表达式中的完整类型?如果没有,如何删除错误?我正在使用 gcc 4.7 进行编译。
您的代码在 C++11 有效,它定义了显示为 decltype 操作数的顶级函数调用不会引入临时函数,即使该调用是 prvalue。
添加此规则是为了使您的代码有效,并防止返回类型(如果是类模板专用化)的实例化,否则需要确定析构函数的访问限制。
decltype
需要一个有效的表达式,你当然可以有一个涉及不完整类型的有效表达式。但是,您情况下的问题是
template<class U>
auto check(U const&) -> typename U::value_type;
当U
为seq<foo>
时,其返回类型为foo
。不能按值返回不完整的类型,因此最终会得到格式不正确的表达式。您可以使用返回类型,例如 void_<typename U::value_type>
(带template<typename T> struct void_ {};
),您的测试似乎有效。
相关文章:
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 表观调用前面的表达式必须具有指向 func 类型的指针
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- 表达式必须具有类类型 vs.
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 非类类型表达式的静态类型与动态类型之间的差异
- 如何确定涉及 C++ 中除法的算术表达式的数据类型
- 结构化绑定初始值设定项表单 { 赋值表达式 } 对于 clang 上的数组类型失败
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 带有数组类型表达式的错误分配
- 表示函数参数的元组的类型表达式
- 如何确定撤销类型表达式的更大类型
- c++ 11中有新的函数类型表达式格式吗?