In all modern C ++ compilers I have worked with, the following is legal:
std::array<float, 4> a = {1, 2, 3, 4};
I am trying to create my own class that has similar constructive semantics, but I am facing an annoying problem. Consider the following attempt:
#include <array> #include <cstddef> template<std::size_t n> class float_vec { private: std::array<float, n> underlying_array; public: template<typename... Types> float_vec(Types... args) : underlying_array{{args...}} { } }; int main() { float_vec<4> v = {1, 2, 3, 4}; // error here }
When using int literals like the one above, the compiler complains that it cannot implicitly convert int to float . I think it works in the std::array example, though, since the specified values ββare compile-time constants, which are known to be in the float domain. Here, on the other hand, the variational pattern uses int for parameter types, and the conversion takes place in the list of constructor initializers, where the values ββare unknown at compile time.
I do not want to do an explicit cast in the constructor, since then it will allow all numeric values, even if they cannot be represented by float .
The only thing I can think of to get what I want is to somehow have a variable number of parameters, but of a certain type (in this case, I would like a float ). I know std::initializer_list , but I would also like to provide the number of parameters at compile time.
Any ideas? Is what I want even with C ++ 11? Anything new suggested for C ++ 14 that solves this?
c ++ arrays c ++ 11 variadic-templates
Jo bates
source share