《C++20设计模式》学习笔记-CRTP例子代码测试

静态多态的例子完整代码如下

import <iostream>;
import <string_view>;

using namespace std;

template <typename TImpl>
class Notifier {
  public:
    void AlertSMS(string_view msg)
    {
        impl().SendAlertSMS(msg);
    }

    void AlertEmail(string_view msg)
    {
        impl().SendAlertEmail(msg);
    }
  private:
    TImpl& impl() { 
       return static_cast<TImpl&>(*this); 
    }
    friend TImpl;
};

template <typename TImpl>
void AlertAllChannels(Notifier<TImpl>& notifier, string_view msg)
{
    notifier.AlertEmail(msg);
    notifier.AlertSMS(msg);
}

struct TestNotifier: public Notifier<TestNotifier>
{
    void SendAlertSMS(string_view msg)
    {
        std::cout << "Sending SMS: " << msg << std::endl;
    }

    void SendAlertEmail(std::string_view msg)
    {
        std::cout << "Sending Email: " << msg << std::endl;
    }
};

int main()
{
   TestNotifier tn;
   AlertAllChannels(tn,"Testing");
   return 0;
}

参考Makefile

CC=g++
CXXFLAGS=-std=c++20 -fmodules-ts 
C20FLAGSiostream=-x c++-system-header iostream
C20FLAGSstring=-x c++-system-header string_view

notify:notify.o
	$(CC) -o $@ $^ 
.cpp.o:
	$(CC) $(CXXFLAGS) $(C20FLAGSiostream)
	$(CC) $(CXXFLAGS) $(C20FLAGSstring)
	$(CC) $(CXXFLAGS) -c $^ 
clean:
	@rm -f *.o notify
	@rm -rf gcm.cache

运行结果

$ ./notify
Sending Email: Testing
Sending SMS: Testing

使用concept代替模板基类的例子如下:

import <iostream>;
import <string_view>;

using namespace std;

template <typename TImpl>
concept IsANotifier = requires(TImpl impl) {
    impl.AlertSMS(string_view());
    impl.AlertEmail(string_view());
};

template <IsANotifier TImpl>
void AlertAllChannels(TImpl& impl, string_view msg)
{
    impl.AlertEmail(msg);
    impl.AlertSMS(msg);
}

struct TestNotifier
{
    void AlertSMS(string_view msg)
    {
        std::cout << "Sending SMS: " << msg << std::endl;
    }

    void AlertEmail(std::string_view msg)
    {
        std::cout << "Sending Email: " << msg << std::endl;
    }
};

int main()
{
   TestNotifier tn;
   AlertAllChannels(tn,"Testing");
   return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值