What exactly is or was the purpose of C++ function-style casts?

后端 未结 6 1935
Happy的楠姐
Happy的楠姐 2020-11-30 07:17

I am talking about \"type(value)\"-style casts. The books I have read pass over them quickly, saying only that they are semantically equivalent to C-style casts, \"(type) va

6条回答
  •  孤街浪徒
    2020-11-30 07:55

    Function style casts bring consistency to primitive and user defined types. This is very useful when defining templates. For example, take this very silly example:

    template
    T silly_cast(U const &u) {
      return T(u);
    }
    

    My silly_cast function will work for primitive types, because it's a function-style cast. It will also work for user defined types, so long as class T has a single argument constructor that takes a U or U const &.

    template
    T silly_cast(U const &u) {
        return T(u);
    }
    
    class Foo {};
    class Bar {
    public:
        Bar(Foo const&) {};
    };
    
    int main() {
        long lg = 1L;
        Foo f;
        int v = silly_cast(lg);
        Bar b = silly_cast(f);
    }
    

提交回复
热议问题