11

I'm using following code with C++11 and getting a error that I'm not allowed to use typeof !

What is the problem and how to fix this ?

The error :

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

Here is my code :

#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 is like this :

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) {}
 };
Mohsen Sarkar
  • 5,910
  • 7
  • 47
  • 86
  • 25
    How about "C++ doesn't have `typeof`"? – Xeo Apr 18 '13 at 10:16
  • 3
    Use `decltype` instead. – masoud Apr 18 '13 at 10:17
  • 1
    Alternatively, you could write a function template which can infer the type, e.g. `make_nvp(#Field,Field)`. This will also work in older versions of the language without `decltype`. – Mike Seymour Apr 18 '13 at 10:21
  • Agree with @MikeSeymour. To clarify: class templates do not have Template Argument Deduction, which is why the standard has a `std::make_pair(T, U)` to create a `std::pair`. Clearly, `make_nvp` would be a template function that returns a `sql_nvp`, using Template Argument Deduction to figure out the `Field` type. – MSalters Apr 18 '13 at 11:40
  • 1
    In defence of OP a lot of compilers had typeof with variable semantic, some with underscores, etc. Hence the start-over with decltype. Plus Javascript, C# spell it this way. – emsr Apr 19 '13 at 12:14
  • see http://stackoverflow.com/questions/1986418/typeid-and-typeof-in-c – Marius Bancila Apr 29 '13 at 08:29
  • technically, `typeid` in C++ is more like `typeof` operator found in other languages like C# but certainly here the author was looking for `decltype` –  Apr 29 '13 at 08:21

1 Answers1

30

What you are looking for is decltype():

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

C++ does not have an operator called typeof.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • 4
    It might be worth mentioning that there are/were differences between `typeof` and `decltype`. Depending on which compiler and version provided `typeof(X)`, it is more like `std::decay::type` than raw `decltype(X)`. – Daniel Frey Apr 18 '13 at 15:42
  • 2
    @blue: No need. The OP is explicitly writing: "*I'm using following code with C++11*" – Andy Prowl Apr 18 '13 at 22:10