2013-04-18 184 views
8

我在C++ 11中使用以下代码,并得到一个我不允许使用的错误typeof为什么C++不允许使用typeof?

什么问题以及如何解决这个问题?

错误:

Error 10 error C2923: 'typeof' is not a valid template type argument for parameter 'C' 

这里是我的代码:

#define HIBERLITE_NVP(Field) hiberlite::sql_nvp< typeof(Field) >(#Field,Field) 


class Person{ 
friend class hiberlite::access; 
template<class Archive> 
void hibernate(Archive & ar) 
{ 
    ar & HIBERLITE_NVP(name); //ERROR 
    ar & HIBERLITE_NVP(age); //ERROR 
    ar & HIBERLITE_NVP(bio); //ERROR 
} 
public: 
string name; 
double age; 
vector<string> bio; 
}; 

sql_nvp是这样的:

template<class C> 
class sql_nvp{ 
public: 
    std::string name; 
    C& value; 
    std::string search_key; 

    sql_nvp(std::string _name, C& _value, std::string search="") : name(_name), value(_value), search_key(search) {} 
}; 
+25

“C++没有'typeof'”? – Xeo

+3

改为使用'decltype'。 – deepmax

+1

或者,您可以编写一个可以推断出类型的函数模板,例如'make_nvp(#场,场)'。这也可以在没有'decltype'的老版本语言中工作。 –

回答

27

你在找什么是decltype()

#define HIBERLITE_NVP(Field) hiberlite::sql_nvp< decltype(Field) >(#Field,Field) 
//            ^^^^^^^^ 

C++没有名为typeof的运算符。

+2

值得一提的是'typeof'和'decltype'之间存在着差异。根据编译器和版本提供的'typeof(X)',它更像是'std :: decay :: type'而不是原始的'decltype(X)'。 –

+1

noone提到decltype仅在C++ 11中可用? – blue

+2

@blue:不需要。 OP明确写道:“*我在C++ 11 *中使用以下代码” –