如何优雅地利用C++编程从1乘到20?

这篇博客通过不同版本的C++编程展示了如何从1乘到20,包括数学家的简洁版本,语言学家的语法特性展示,历史学家的`void main()`,敏捷开发的快速实现,面向对象的接口与继承应用,提前优化的并行处理,黑魔法般的底层技术,以及宏和模板元编程的极致泛型。作者以幽默的方式探讨了C++的多样性和灵活性。
摘要由CSDN通过智能技术生成

知乎的一个问题:

 答主:小白白。

数学家版本:

(简单利索,深藏功与名)

#include <iostream>
#include <cmath>
int main()
{
    std::cout << std::tgamma(20 + 1) << std::endl;
}

语言学家版本:

(语言学家,你懂得,恨不得把所有语法特性都派上用场)

#include <iostream>
#include <utility>

template<std::size_t...I> constexpr auto foo(std::index_sequence<I...>) { return ((I+1) * ...); }

int main() 
{
    std::cout << foo(std::make_index_sequence<20>()) << std::endl;
}

历史学家版本:

(void main() 有没有嗅到浓厚的历史气息?)

#include <stdio.h>
void main(void) {
    int i;
    long long j;
    for(i = 1, j = 1;i <= 20; j *= i++);
        printf("%lld", j); 
}

敏捷开发上线1.0版本:

(可以说是非常敏捷了)

#include <stdio.h>
int main() {
    //printf("%d", 1*2*3*4*5*6*7*8*9*10);
    printf("%lld", (long long)1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20);
}

面向对象专家版本:

(好家伙,一个简单的问题,愣是祭出了接口、继承、虚函数、虚继承、智能指针等一大堆东西出来,这很面向对象)

#include <iostream>
#include <string>
#include <memory>

struct IBaseInterface {
    virtual ~IBaseInterface() = 0;
};
inline IBaseInterface::~IBaseInterface() = default;

struct IDataProvider : virtual public IBaseInterface {
    virtual int first() = 0;
    virtual int last() = 0;
    virtual int next(int v) = 0;
};

struct ICalculator : virtual public IBaseInterface {
    virtual long long calc(IDataProvider *) = 0;
};

struct IPrinter : virtual public IBaseInterface {
    virtual void print(const std::string &) = 0;
};

struct ISerializer : virtual public IBaseInterface {
    virtual std::string serialize(long long value) = 0;
};

struct IRunnable : virtual public IBaseInterface {
    virtual void run() = 0;
};

class Foo : virtual public IRunnable {
    std::shared_ptr<IDataProvider> m_dp;
    std::shared_ptr<ICalculator> m_c;
    std::shared_ptr<ISeria
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值