【问题标题】:What operator to overload when class is passed as argument to printf()当类作为参数传递给 printf() 时要重载的运算符
【发布时间】:2015-12-03 11:17:54
【问题描述】:

我有一个 int,我在这里使用模板解决方案封装为“属性”:

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;
    }
};

但是,如果将属性标识符作为参数传递给需要可变数量参数的函数,例如 printf(),则传递类指针值而不是 int 值。

是否有我可以重载的运算符以便传递 int 值?

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可以将static_cast 运算符用于类的对象。

    例如

    int value = 10;
    Property<int> p( value );
    
    printf( "%d\n", static_cast<int>( p ) );
    

    在这种情况下是转换运算符

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

    将被调用。

    【讨论】:

      【解决方案2】:

      在将类的对象传递给printf 之前,您必须自己执行转换。将大多数用户定义类型的对象传递给可变参数函数具有实现定义的行为:

      [expr.call]/7:

      传递具有非- 普通复制构造函数、非普通移动构造函数或非普通析构函数,没有对应的 参数,有条件地支持实现定义的语义

      【讨论】:

        【解决方案3】:

        没有。从技术上讲,编译器不知道需要哪种类型。 (请注意,一些编译器会提供警告,因为它们知道格式字符串的语法并且可以检查参数,但据我所知,这不是强制性的,也没有定义实际的参数类型。)所以没有办法编译器在搜索强制转换运算符时知道它需要寻找哪种类型。

        您需要显式转换。在您的情况下,您可以:

        int a;
        Property<int> prop(a);
        a = 10;
        printf("%d\n", static_cast<int>(prop));
        

        【讨论】:

        • 谢谢。我没有收到 Microsoft Visual Studio 2013 的警告,所以我必须搜索所有案例。我希望我会使用 Xcode,我知道它会检查该格式字符串。
        猜你喜欢
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多