英文:
How to write a class template to handle different data members?
问题
I would like to write a class template that behaves as follows:
-
If I pass
Type_1
as an argument of the class instance, having then something likeTestClass<MessageType::Type_1> t1
, I want to see both members of the struct Message. -
If I pass
Type_2
, I want to see only the integermember_2
and NOT themember_1
inside theMessage
struct.
So, in a nutshell, I would like to decide what are the members according to the template parameter.
#include <string>
enum class MessageType
{
Type_1,
Type_2
};
template <MessageType messageType>
class TestClass
{
public:
struct Message
{
std::string member_1;
int member_2{0};
};
};
I've tried to use conditional statements but I got compiler errors.
英文:
I would like to write a class template that behaves as follows:
-
If I pass
Type_1
as an argument of the class instance, having then something likeTestClass<MessageType::Type_1> t1
, I want to see both memebers of the struct Message. -
If I pass
Type_2
, I want to see only the integermember_2
and NOT themember_1
inside theMessage
struct.
So, in a nutshell, I would like to decide the what are the members according to the template parameter.
#include <string>
enum class MessageType
{
Type_1,
Type_2
};
template <MessageType messageType>
class TestClass
{
public:
struct Message
{
std::string member_1;
int member_2{0};
};
};
I've tried to use conditional statements but I got compiler errors
答案1
得分: 1
The provided code snippet is as follows:
无法确定以下内容在您的情况下是否可行。如果可能的话,我会重构为具有两种不同类型,然后通过单独模板的专门化来选择其中一种:
#include <iostream>
#include <string>
enum class MessageType
{
Type_1,
Type_2
};
struct message1 { std::string member1; int member2; };
struct message2 { std::string member1; };
template <MessageType mt> struct select_type;
template <> struct select_type<MessageType::Type_1> { using type = message1; };
template <> struct select_type<MessageType::Type_2> { using type = message2; };
template <MessageType select>
struct TestClass
{
using message_type = typename select_type<select>::type;
};
int main()
{
return 0;
}
如果您需要进一步的帮助,请告诉我。
英文:
Whether the following is viable in your case depends. If possible I would refactor to have two different types and then pick one via specialization of a separate template:
#include <iostream>
#include <string>
enum class MessageType
{
Type_1,
Type_2
};
struct message1 { std::string member1; int member2; };
struct message2 { std::string member1; };
template <MessageType mt> struct select_type;
template <> struct select_type<MessageType::Type_1> { using type = message1; };
template <> struct select_type<MessageType::Type_2> { using type = message2; };
template <MessageType select>
struct TestClass
{
using message_type = typename select_type<select>::type;
};
int main()
{
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论