使用带有重载操作符++的c++ decltype(预增量)
Using C++ decltype with overloaded operator++ (preincrement)
对于某些模板typename,我想创建一个typedef,它是T::operator++()(又名T的预增量操作符)声明的返回类型。
我在网上没有找到任何明确的内容,尽管确实有一些提到了带有预增量的decltype。所以我尝试了一些东西,唯一真正有效的似乎是一个肮脏的黑客。你觉得这个怎么样?
struct S { // dummy type to simulate a real one I have
int operator++() { return 0; } // note: return type is not S&
int operator++(int) { return 0; }
};
int main() {
// this works:
typedef decltype(++S()) T1;
// so why doesn't this work?
// error: lvalue required as increment operand
// typedef decltype(++int()) T2;
// this works, but seems dirty:
typedef decltype(++*(int*)nullptr) T3;
typedef decltype(++*(S*)nullptr) T4;
// I also haven't figured out how to disambiguate this,
// though it's moot because int::operator++ is not a thing
// error: ‘S::operator++’ refers to a set of overloaded functions
// typedef decltype(S::operator++) T5;
}
我使用的是GCC 4.6.2。我试了一下Clang,但也好不到哪里去。
内置类型和用户定义类型的左值在临时类型的情况下是不同的:在您的示例中,临时
int
是右值,但临时S
是左值
编辑:从技术上讲,所有临时值都是右值,但操作符与用户定义类型的工作方式不同,因为它们实际上是伪装的常规函数。这意味着您可以使用它们做一些非右值的事情,例如将S()
作为默认赋值操作符的左侧!
使用declval
在未求值的上下文中获取任意类型的左值或右值:
#include <utility>
// declval<T&> yields an lvalue, declval<T> an rvalue
typedef decltype(std::declval<int&>()++) T1; // int
typedef decltype(++std::declval<int&>()) T2; // int&
typedef decltype(std::declval<S&>()++) T3; // S
typedef decltype(++std::declval<S&>()) T4; // S&
相关文章:
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- C++decltype和圆括号-为什么
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 如何从"decltype()"获取函数参数的数量<funtion>?
- Confusion: decltype vs std::function
- decltype(1, t) 应该是 l 值引用吗?(编译器不同意)
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- 无效 f(int) 的模板和 decltype
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- decltype:使用指针访问类的静态成员
- decltype() 不适用于正在编译的类模板
- 在部分模板专用化中使用 decltype
- 非静态成员函数的 decltype 格式不正确吗?
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- "decltype(&ordenary_func)"和"decltype"(ordenary_func)之间的区别
- 指向具有 decltype 的函数的指针向量
- About std::unique_prt() and decltype()
- 来自 decltype 的意外输出类型