静态多态的例子完整代码如下
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;
}