c++ - Why can't a struct be passed as value as template non-type parameter? -
non-type template parameters ones aren't types, example:
template<int x> void foo() { cout << x; }
there other options int
in case, , i'd refer this great answer.
now, there's 1 thing bugs me: structs. consider:
struct triple { int x, y, z; }; triple t { 1, 2, 3 }; template<triple const& t> class foo { };
now, using normal nontype reference semantics, can write:
foo<t> f;
what's worth noting here t
can't constexpr
or const
, because implies internal linkage, means line won't compile. can bypass declaring t
const extern
. might bit weird, 1 made me wonder why isn't possible:
foo<triple { 1, 2, 3 }> f;
we decent error compiler:
error:
triple{1, 2, 3}
not valid template argument typeconst triple&
because not lvalue.
we can't specify triple
in template value, because that's disallowed. however, fail understand real problem small line of code. what's reasoning behind not allowing using structs value parameters. if can use 3 int
s, why not struct of 3 ints? if has trivial special members, shouldn't different in handling 3 variables.
i think "because it's pain in mikta both specify , implement" major reason don't have this. sure, easy make bit work, people complain how using struct template parameters not work in same situations other template parameters (consider partial specializations, or operator==
).
in opinion it's messy whole cake, , getting 1 tiny slice isn't satisfying enough, , possibly more frustrating. making tiny bit work won't give me more power following, has additional advantage of working kinds of stuff (including partial specializations) out of box.
template <int x, int y, int z> struct meta_triple { // static value getters static constexpr auto x = x; static constexpr auto y = y; static constexpr auto z = z; // implicit conversion triple constexpr operator triple() const { return { x, y, z }; } // function call operator 1 can force conversion triple // meta_triple<1,2,3>()() constexpr triple operator()() const { return *this; } };
Comments
Post a Comment