c++ - 函数模板特化以强制使用类型的枚举值

标签 c++ templates template-specialization partial-specialization

给定消息类型和特定于消息类型的数据结构,需要一个函数来发送消息:

enum class MsgType
{
    msgInt,
    msgDouble,
    msgString
};

template < some template here >
void sendMessage(MsgType type, T value);

我希望通过以下方式调用此函数:

sendMessage( MsgType::msgInt, 42 );
sendMessage( MsgType::msgString, "Answer to the life, etc,etc.");
//sendMessage( MsgType::msgDouble, "Should not compile");
//sendMessage<MsgType::msgString>( "That is easy!" );

如何实现前面描述的模板函数特化?

注意:如果可能,使用 C++11,但 C++14 也是可以接受的。

编辑:

当前的实现,它只接受 MsgType 作为模板参数(而不是函数参数)。

template<MsgType Id, typename T>
void sendMessage(T data);

template<>void sendMesssage<MsgType::msgNumCar, int>( int data ){ //...   }
template<>void sendMesssage<MsgType::msgInt, int>( int data ){ //...   }
template<>void sendMesssage<MsgType::msgString, string>( string data ){ //...   }
// A call
sendMessage<MsgType::msgNumCar>( 42 );

最佳答案

模板可以有编译时已知的常量参数。您可以执行以下操作:

enum MsgType {
    msgInt,
    msgDouble,
    msgString
};

template<int>
struct Message { };

template<>
struct Message<MsgType::msgInt> {
    static void send(int value) { cout << "int: " << value; }
};

template<>
struct Message<MsgType::msgDouble> {
    static void send(double value) { cout << "double: " << value; }
};

template<>
struct Message<MsgType::msgString> {
    static void send(const char* value) { cout << "string: " << value; }
};

并调用它:

Message<MsgType::msgInt>::send(5);
Message<MsgType::msgDouble>::send(3.14);
Message<MsgType::msgString>::send("hello");

// will not compile
//Message<MsgType::msgDouble>::send("should not compile");

注意模板参数必须是常量(即在编译时已知)。这意味着以下代码将无法编译:

int type = MsgType::msgInt;
Message<type>::send(123);

但是,为什么不为 sendMessage 创建 3 个重载?

关于c++ - 函数模板特化以强制使用类型的枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38081498/

相关文章:

c++ - 虚成员函数定义

c++ - Visual C++ 窗体、简单消息框和将文本从文本字段分配给字符串时出错

c++ - 模板与类似的非模板函数

c++ - 由于范围有限,比较总是错误的...使用模板

c++ - 返回 std::function 的函数的返回类型

c++ - 将字符串的排列与存储在文本文件中的单词进行比较

c++ - 为什么在使用 "using namespace std;"和 "bits/stdc++.h"时会在此代码中出现错误?

c++ - 如何专门化模板类的某些成员?

c++ - 模板类中的命名空间特化

c++ - 特化一个成员函数而不是整个类