Jerry YY Rain
Jerry YY Rain

Reputation: 4392

How can I get different type in function template

I define below function template, But I meet some problem. Please kindly help me out. Thanks!

template <typename T>
void Insert(CMyObj obj_, std::vector<T>& vec_)
{
    if(T is bool type)
        vec_.push_back(obj_.AsBool());
    if(T is string type)
        vec_.push_back(obj_.AsString());
}

I can call function template as below, How should I implement my Insert().

CMyObj  obj;
std::vector<bool> vec1;
Insert<bool>(obj, vec1);

std::vector<string> vec2;
Insert<string>(obj, vec2);

Upvotes: 0

Views: 46

Answers (2)

heinrichj
heinrichj

Reputation: 552

First of all, if the template parameter can be deduced from the arguments (which it can in this case) you can simply call it via "Insert(obj, vec1)": if vec1 is std::vector<bool>, T will be bool etc...

Secondly, I would define a second function template, specifically to extract a typed value from your variant-like CMyObj:

template <typename T>
T GetValue(const CMyObj& obj); // Note: no definition

// These should be inline or in a .cpp file to prevent linker issues
template <>
inline bool GetValue(const CMyObj& obj) { return CMyObj.AsBool(); }

template <>
inline std::string GetValue(const CMyObj& obj) { return CMyObj.AsString(); }

You can then implement Insert as:

template <typename T>
void Insert(CMyObj obj_, std::vector<T>& vec_)
{
  vec_.push_back(GetValue<T>(obj_));
}

If you try to insert it into a vector with a value type for which GetValue has not been specialized, it won't compile. Which is what you'd want I guess.

Upvotes: 2

Singh
Singh

Reputation: 361

Don't know what is the error you are facing, but you can change your code as below:-

template <typename T>
void Insert(T obj_, std::vector<T>& vec_)
{
        vec_.push_back(obj_);
}




CMyObj  obj;
std::vector<bool> vec1;
Insert<bool>(obj.AsBool(), vec1);

std::vector<string> vec2;
Insert<string>(obj.AsString(), vec2);

Upvotes: 0

Related Questions