簡體   English   中英

成員變量的C ++ typename

[英]C++ typename of member variable

是否可以獲取成員變量的typename? 例如:

struct C { int value ; };

typedef typeof(C::value) type; // something like that?

謝謝

不是在C ++ 03中。 C ++ 0x引入了decltype

typedef decltype(C::value) type;

一些編譯器有一個typeof的擴展,雖然:

typedef typeof(C::value) type; // gcc

如果你對Boost沒問題,他們就有了一個

typedef BOOST_TYPEOF(C::value) type;

只有在處理函數中的類型時才可以

struct C { int value ; };

template<typename T, typename C>
void process(T C::*) {
  /* T is int */
}

int main() {
  process(&C::value); 
}

它不適用於參考數據成員。 C ++ 0x將允許decltype(C::value)更容易地做到這一點。 不僅如此,它還允許decltype(C::value + 5)decltype任何其他花哨的表達式東西。 Gcc4.5已經支持它了。

可能不是您正在尋找的,但從長遠來看可能是更好的解決方案:

struct C {
  typedef int type;
  type value;
};

// now we can access the type of C::value as C::type
typedef C::type type;

這不是你想要的,但它確實允許我們隱藏C::value的實現類型,以便我們以后可以更改它,這是我懷疑你所追求的。

這取決於你需要做什么,但你會做如下:

#include <iostream>
using namespace std;

struct C
{
    typedef int VType;
    VType value;
};

int main()
{
    C::VType a = 3;
    cout << a << endl;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM