explicit specialization 显式指定

本文介绍了一个C++程序示例,展示了如何使用模板函数与显式特化来实现不同类型消息的广播。通过具体的代码实现,读者可以了解到模板函数的基本用法及其针对特定类型进行特化的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//explicit specialization 显式指定
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

struct msg
{
    string title;
    string content;
};

//非模板函数
void Broadcast(const string& msg);

//模板函数
template <typename T>
void Broadcast(const T& msg);

//explicit specialization 显式指定
template<> void Broadcast<msg>(const msg& msg);    

int main(void)
{
    string simpleMsg = "You just receive one message";
    int msgNum = 73357;
    msg msg;
    msg.title = "Attention";
    msg.content = "Perimeter has been breached, evacuate to section 7.";

    Broadcast(simpleMsg);
    Broadcast(msgNum);
    Broadcast(msg);
    
    cin.get();
    return 0;
}

void Broadcast(const string& msg)
{
    cout << "Notice: " << msg << endl;
}

template <typename T>
void Broadcast(const T& msg)
{
    cout << "No: " << msg << endl;
}

template<> void Broadcast<msg>(const msg& msg)
{
    cout << endl;
    cout << "************************************" << endl;
    cout << "Title: " << msg.title << endl;
    cout << "Content: " << msg.content << endl;
    cout << "************************************" << endl;
}

 

 

转载于:https://www.cnblogs.com/heben/p/9308137.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值