2

I have an int which I have encapsulated as a 'property' using the template solution here:

https://stackoverflow.com/a/4225302/3717478

template<typename T>
class Property
{
protected:
    T& _value;

public:
    Property(T& value) : _value(value)
    {
    }   // eo ctor

    Property<T>& operator = (const T& val)
    {
        _value = val;
        return *this;
    };  // eo operator =

    operator const T&() const
    {
        return _value;
    };  // eo operator ()

    T& operator() ()
    {
        return _value;
    }
    T const& operator() () const
    {
        return _value;
    }
};

However if the property identifier is passed as an argument to a function expecting a variable number of arguments, such as printf(), the class pointer value is passed instead of the int value.

Is there an operator that I can overload so that the int value is passed instead?

Community
  • 1
  • 1
user3717478
  • 863
  • 1
  • 8
  • 15

3 Answers3

3

You can use static_cast operator with objects of the class.

For example

int value = 10;
Property<int> p( value );

printf( "%d\n", static_cast<int>( p ) );

In this case the conversion operator

operator const T&() const
{
    return _value;
};  // eo operator ()

will be called.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

No. The compiler does not know, technically, which type is required. (Note that some compilers offer warnings because they know the syntax of the format string and can check the arguments, but that is, as far as I know, not compulsory and does not define the actual argument types.) So there is no way for the compiler to know which type it would need to look for, when searching for a cast operator.

You need to explicitly cast. In your case you could:

int a;
Property<int> prop(a);
a = 10;
printf("%d\n", static_cast<int>(prop));
Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69
  • Thanks. I didn't get a warning with Microsoft Visual Studio 2013 so I have to search for all cases. I expect I would have done with Xcode which I know examines that format string. – user3717478 Dec 03 '15 at 12:00
2

You have to perform the conversion yourself before passing an object of your class to printf. Passing objects of most user-defined types to a varargs function has implementation defined behaviour:

[expr.call]/7:

Passing a potentially-evaluated argument of class type (Clause 9) having a non- trivial copy constructor, a non-trivial move constructor, or a non-trivial destructor, with no corresponding parameter, is conditionally-supported with implementation-defined semantics

Simple
  • 13,992
  • 2
  • 47
  • 47