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

后端 未结 2 1067
半阙折子戏
半阙折子戏 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 02:56

    Yes, as Michael pointed out in his answer to your previous question, in C++0x you'll be able to use an initializer list to pass an arbitrary number of arguments to your ctor. In your case, the code would look something like:

    template 
    class point { 
        T X[dims];
    public:
        point(std::initializer_list const &init) { 
            std::copy(init.begin(), init.begin()+dims, X);
        }
    };
    

    You could create a point object with this something like:

    point<3, double> x{0.0, 0.0, 0.0};
    

    Personally, I'm not sure I like the basic design very well though. In particular, I'd rather see X turned into an std::vector, and determine the number of dimensions strictly from the parameter list that was passed instead of having it as a template argument:

    template 
    class point { 
        std::vector X;
    public:
        point(std::initializer_list init) {
            std::copy(init.begin(), init.end(), std::back_inserter(X));
        }
    };
    

    This does have some trade-offs though -- points with a different number of dimensions are still the same type. For example, it basically asserts that it's reasonable to assign a 2D point to a 3D point, or vice versa.

提交回复
热议问题