繁体   English   中英

将C ++ decltype与重载的operator ++一起使用(预增量)

[英]Using C++ decltype with overloaded operator++ (preincrement)

对于某些模板类型名,我想创建一个typedef,它是T :: operator ++()的声明返回类型(又名T的preincrement运算符)。

我没有在网上找到任何确定的内容,尽管肯定有人提到过带增量代码的decltype。 因此,我尝试了一些尝试,并且唯一可行的尝试似乎是一个肮脏的hack。 你觉得这怎么样?

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是左值。

编辑:从技术上讲,所有临时变量都是右值,但是运算符与用户定义的类型不同,因为它们实际上是变相的常规函数​​。 这意味着您可以使用它们执行一些非常不类似于rvalue的操作,例如将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&

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM