Thompson Liu
Thompson Liu

Reputation: 145

c++ deciding the dynamic template type

Inside a template function, is there any way that I can tell the type of the template being used. I'd like to do something as follows:

For example:

template <typename T>
void function(T t) {
    if (T instancof int)     auto object = IntObject();
    else if (T instanceof string)    auto object = StringObject();
}

IntObject and StringObject are just two different types. If this function is applied as follows:

function<int>(5)

I'd like to construct an instance of IntObject

The Concrete code is as follows:

bool not_null = true;
if (key instanceof uint64_t) {
    auto object = ObjectWithUInt64Key();
else if (key instanceof std::string) {
    auto object = ObjectWithStringKey();

auto result = get<CascadeType>(key,ver,subgroup_index,shard_index);
for (auto& reply_future:result.get()) {
    object = reply_future.second.get();
    ver = object.previous_version_by_key; 
    not_null = not_null && !object.is_null();
}
if (not_null) 
    return object;

Upvotes: 0

Views: 48

Answers (1)

super
super

Reputation: 12968

Looks like all you need is to make a CreateObjectWithKey template function, then add some full specialization to it.

template <typename T>
auto CreateObjectWithKey();

template <>
auto CreateObjectWithKey<int>() {
    return ObjectWithIntKey();
}

template <>
auto CreateObjectWithKey<std::string>() {
    return ObjectWithStringKey();
}

Then you can use it as follows

template <typename T>
void function(T t) {
    auto object = CreateObjectWithKey<T>();
}

Upvotes: 1

Related Questions