简体   繁体   English

如何在模板 function 中使用不同的结构作为模板参数?

[英]How can I use different struct as template argument in a template function?

I am writing a template function like that:我正在编写这样的模板 function:

template<typename T>
std::string EncodeData(int DataType, T Data, std::string ReadCommandID, std::string& ThisID);

The type T that I want to use is some different structs, for example:我想使用的类型T是一些不同的结构,例如:

struct A
{
    int A_data;
    bool A_data_2;
    // etc.......
};

struct B
{
    double B_data;
    char B_data_2;
    // etc.......
};

I want the function can access different member variables depends on different struct passing to T ,so I wrote such code:我希望 function 可以访问不同的成员变量取决于传递给T的不同struct ,所以我写了这样的代码:

template<typename T>
std::string EncodeData(int DataType, T Data, std::string ReadCommandID, std::string& ThisID)
{
    if(std::is_same<T, A>{})
    {
        // Do something with Data.A_data and Data.A_data_2
    }
    else if(std::is_same<T, B>{})
    {
        // Do something with Data.B_data and Data.B_data_2
    }
    // other code.
}

And use it:并使用它:

A data={100,false};
std::string id;
std::string result = EncodeData<A>(0,data,"read_id_xxxxxxxx",id);

But when I compile it, the following error happened:但是当我编译它时,发生了以下错误:

error C2039: "B_data": is not a member of "A".    
error C2039: "B_data_2": is not a member of "A".

How can I fix this?我怎样才能解决这个问题? Or what else I can do to solve this problem in one single function?或者我还能做些什么来在一个 function 中解决这个问题?

PS I'm using MSVC Compiler(Visual Studio 2019) PS我正在使用 MSVC 编译器(Visual Studio 2019)

What else I can do to slove this problom in one single function ?我还能做些什么来解决一个 function中的这个问题?

This is not possible under compiler.这在编译器下是不可能的。 However, in C++17 you have if constexpr to do such:但是,在 C++17 中,您可以使用if constexpr来执行此操作:

template<typename T>
std::string EncodeData(int DataType, T const& Data, std::string const& ReadCommandID, std::string& ThisID)
{
    if constexpr (std::is_same_v<T, A>)
    {
        // Do something with Data.A_data and Data.A_data_2
    }
    else if constexpr (std::is_same_v<T, B>)
    {
        // Do something with Data.B_data and Data.B_data_2
    }
}

For C++11 you still need two functions.对于 C++11,您仍然需要两个函数。 Therefore, I would suggest having a function overload for each, which might be more readable than having templates.因此,我建议为每个重载一个 function,这可能比使用模板更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM