template class: ctor against function -> new C++ standard

后端 未结 2 1074
半阙折子戏
半阙折子戏 2021-01-16 02:21

in this question:
template; Point<2, double>; Point<3, double>
Dennis and Michael noticed the unreasonable foolishly implemented constructor.
They we

2条回答
  •  滥情空心
    2021-01-16 03:02

    Since the array is public, it is an option to omit the constructor and allow aggregate initialization (like boost::array for example).

    Point<2, int> p = {1, 2};
    

    This is no worse than having to call a create function. (The create function might still be handy as a utility.)


    In C++0x you will be able to have all sorts of coolness. For example, play with variadic templates, to have it checked at compile-time if the constructor is called with a right number of arguments. (The following could also check if the arguments ...U are all of type T, with some more metaprogramming fun, but it might not be absolutely necessary.)

    //helper to copy variable amount of arguments into an array
    namespace detail {
    
    template 
    void copy_variadic(T* p, U value)
    {
        *p = value;
    }
    
    template 
    void copy_variadic(T* p, First var, Rest ...args)
    {
        *p = var;
        copy_variadic(++p, args...);
    }
    } //detail
    
    template < unsigned int dims, typename T >
    struct Point {
    
        T X[ dims ];
    
        Point() : X{}
        {
        }
    
        template 
        Point(U... args) {
            static_assert(sizeof...(args) == dims, "Too many or too few arguments to Point constructor");
            detail::copy_variadic(X, args...);
        }
        //...
    };
    

    (Actually, with some modifications - perfect forwarding - copy_variadic would make a nice addition to my collection of variadic-template utilities, if someone doesn't come and point out a significantly better way.)

提交回复
热议问题