给定消息类型和特定于消息类型的数据结构,需要一个函数来发送消息:
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/