C ++元模板,186个字节
使用我的C答案中的显式公式,元模板正在竞争!
template<int N,int X=N*N+N-1>struct H{enum{I=X/(N+1)-N/2,J=X%(N+1)-N/2-1};S s{(J==-N/2-1?'\n':((I>=J&I>=-J)|(I<=J&I<=-J)?'*':' '))+H<N,X-1>().s};};template<int N>struct H<N,-1>{S s="";};
取消高尔夫:
using S=std::string;
template <int N, int X=N*N+N-1>
struct H{
enum{I=X/(N+1)-N/2,J=X%(N+1)-N/2-1};
S s{(J==-N/2-1 ? '\n' : ( (I>=J&I>=-J)|(I<=J&I<=-J) ?'*':' '))+H<N,X-1>().s};
};
template <int N> struct H<N,-1> {S s="";};
用法:
std::cout << H<5>().s;
不竞争
只是为了好玩:
//T: Tuple of chars
template <char C, char...Tail> struct T { S r=S(1,C)+T<Tail...>().r; };
//specialization for single char
template <char C> struct T<C> { S r=S(1,C); };
//M: Repeated char
template <int N, char C> struct M { S r=S(N,C); };
//U: concatenates T and M
template <class Head, class...Tail> struct U { S r=Head().r+U<Tail...>().r; };
//specialization for Tail=M
template <int N, char C> struct U<M<N,C>> { S r{M<N,C>().r}; };
//specialization for Tail=T
template <char...C> struct U<T<C...>> { S r=T<C...>().r; };
//finally the Hourglass
template <int N, int I=0> struct H {
S s=U<
M<I,' '>,
M<N,'*'>,
T<'\n'>
>().r;
S r{s + H<N-2,I+1>().r + s};
};
//specialization for recursion end
template <int I> struct H<1,I> {
S r=U<
M<I,' '>,
T<'*','\n'>
>().r;
};
用法:
std::cout << H<5>().r;