2

I ran into the following code that defines a function template in a class:

#include <cstdint> class foo { public: enum class magic_type : std::uint32_t { START = 0, BLUE = 0xFF000001, RED, }; struct header_t { uint32_t version; magic_type magic; }; template <typename T> static bool is_of_type(header_t *h) { return (h->magic == T::magic_type); } foo(uint32_t ver, foo::magic_type mag) { header.version = ver; header.magic = mag; } header_t header; }; 

I am finding the implementation of 'is_of_type` confusing. The code as is compiles, so syntactically must be correct. However, this method is not invoked from any other part of the program, so I am not sure what the intent of the function is (lack of documentation). I figured there could be two interpretation of the function:

  1. Return true/false based on the magic type of an object and the specific enum type passed as the function template parameter.

    E.g. An invocation of the method would be:

    foo bar(1.2, foo::magic_type::BLUE); bool temp = bar.is_of_type<foo::magic_type::BLUE>(&(bar.header)); 

    However, in the above case, I am not really passing a type (as in an int, or char, etc). Right? The code does not compile.

  2. Return true/false if the magic type is a valid enum.

    In this case, I am assuming the function does not need to be templated, and could be re-written as:

    static bool is_of_type(header_t *h) { return (h->magic == foo::magic_type); } 

    E.g. of an invocation:

    foo bar(1.2, foo::magic_type::BLUE); bool temp = bar.is_of_type(&(bar.header)); 

    Again, getting compile error. I tried using "typename", but my attempts were futile.

Can someone please help me with proper implementation of is_of_type for the above two cases and an invocation example.

2
  • Incidentally, why did you write new foo… instead of foo bar(1.2, foo::magic_type::BLUE)? Hopefully you’re not using such code, with redundant news, in reality. Commented Jun 9, 2014 at 22:29
  • @KonradRudolph That was a typo, I was trying out different things to get code to compile. Thank you pointing it out. Updated my question. Commented Jun 9, 2014 at 22:37

1 Answer 1

1

The invocation would be with an explicitly specified type, which has a nested static member called magic_type.

For instance, it could be called as follows:

struct test { static foo::magic_type const magic_type; }; foo::magic_type const test::magic_type = 42; 
foo bar{1, foo::magic_type::BLUE}; bar.is_of_type<test>(bar.header); 

The fact that magic_type is used twice, once for an enum class and once for a static variable, is very confusing though.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I understand now. I personally don't like the names used for the enum and variable, but have to work with code as in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.