jeudi 6 décembre 2018

How to return multiple types from a member method

I am trying to write a class method that can return any one member variable value based on value held in DataType struct variable. I have tried below code:

#include <iostream>
struct A
{
    int DataType;/* holds enum value for one of below data data needs to be returned  */
    union /* value of var is one of these needs to be returned */
    {
       int32_t x;
       uint32_t y;
       uint64_t mz;
       bool    b;
       struct         
       {
          char* ptr;
          int len;    
       } str;              
    }data;
};


struct A a1 = { /* value 1 means int32_t, 2 means uint32_t, 3 means uint64_t , 4 means bool and 5 means str */ 2, 32};
//struct A a2 = { /* value 1 means int32_t, 2 means uint32_t, 3 means uint64_t , 4 means bool and 5 means str */ 5, Hello};
class B
{
public:
B(){}
template <>
T GetVar(struct A a0)
{
if (a0.DataType == 2)
return a0.data.y;
if (a0.DataType == 5)
return std::string(a0.data.str.ptr);
return 0;
}
};

int main()
{
  B b1;
  auto d = b1.GetVar(a1);
  std::cout << d << std::endl;
  //auto d1 = b1.GetVar(a2);
  std::cout << d << std::endl;
}

I get compilation error - and I know that error is related to initializing the str member variable of struct A (how to solve this) and also how can the class method return different variable values?

$ c++ -std=c++11 try72.cpp
try72.cpp:26:11: error: explicit specialization in non-namespace scope 'class B'
 template <>
           ^
try72.cpp:27:1: error: 'T' does not name a type
 T GetVar(struct A a0)
 ^
try72.cpp: In function 'int main()':
try72.cpp:40:13: error: 'class B' has no member named 'GetVar'
 auto d = b1.GetVar(a1);
             ^
try72.cpp:42:14: error: 'class B' has no member named 'GetVar'
 auto d1 = b1.GetVar(a2);
              ^
try72.cpp:42:21: error: 'a2' was not declared in this scope
 auto d1 = b1.GetVar(a2);

                 ^

Aucun commentaire:

Enregistrer un commentaire