Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Field of struct as a template parameter

Tags:

c++

templates

I have a code in MSVC 2008:

template< class T, class FieldType, FieldType T::*FieldPtr >
struct EqualBy {
    EqualBy( const FieldType & value ) : m_filedValue( value ) {}
    bool operator()( const T & r ) const {
        return m_filedValue == r.*FieldPtr;
    }
private:
    const FieldType m_filedValue;
};

...

struct S {
    int field1;
    ...
};
typedef EqualBy< S, int, &S::field1 > EqualByField1;

...

typedef std::vector< S > SVect;
SVect v;
SVect::const_iterator found = std::find_if( v.begin(), v.end(), EqualByField1( 42 ) );

it works fine. But now I want to move the EqualByField1 typedef into the struct S. like this

struct S {
    int field1;
...

    typedef EqualBy< S, int, &S::field1 > EqualByField1;
};

to decrease the scope of this typedef and to "beautify" the caller code like this

SVect::const_iterator found = std::find_if( v.begin(), v.end(), S::EqualByField1( 42 ) );

but I got following errors

error C2327: 'S::field1' : is not a type name, static, or enumerator
error C2065: 'field1' : undeclared identifier

The question is: Is there any solution of this problem, except of to derive from S like that

struct SS : public S {
    typedef EqualBy< S, int, &S::field1 > EqualByField1; // it works, but I do not want to derive :)
};

Thanx. And sorry for my ugly english :)

like image 912
borisbn Avatar asked Dec 29 '25 03:12

borisbn


2 Answers

Your question is no ugly :-)
Though I'm not 100% confident that this really meets your aim, the following work-around might help:

struct S {
    int field1;

    template< class T >
    struct TEqualByField1 {
        typedef EqualBy< T, int, &T::field1 > type;
    };
    typedef TEqualByField1< S >::type EqualByField1;
};

Hope this helps

like image 130
Ise Wisteria Avatar answered Dec 30 '25 18:12

Ise Wisteria


Your code is already correct. At least the parts you have shown. The compiler thinks that &S::field1 is &(S::field1). But what you wrote is not, as it correctly wants to have a member pointer.

This appears to be a compiler related problem.

like image 36
Johannes Schaub - litb Avatar answered Dec 30 '25 16:12

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!