【问题标题】:c++ deciding the dynamic template typec++ 决定动态模板类型
【发布时间】:2020-10-08 02:04:15
【问题描述】:

在模板函数中,有什么方法可以告诉我正在使用的模板的类型。我想做以下事情:

例如:

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

IntObject 和 StringObject 只是两种不同的类型。 如果这个函数应用如下:

function<int>(5)

我想构造一个 IntObject 的实例

具体代码如下:

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;

【问题讨论】:

  • 我不确定您所说的“动态类型”是什么意思。还有,InstInstanceStringInstance是什么?
  • 有很多方法可以做到这一点。您可能想稍微澄清一下您的问题。 IntObject 是您的课程之一吗?建成后你想用它做什么?
  • @super 让我知道具体示例是否仍然没有意义
  • 您在问两个不同的问题:对于“如何测试函数模板的类型”,这有帮助吗? stackoverflow.com/a/64254612/1863938 。对于“如何在同一个对象中存储不同类型”,请查看 std::variantvirtual base class

标签: c++ templates


【解决方案1】:

看起来您只需要创建一个CreateObjectWithKey 模板函数,然后为其添加一些完整的特化。

template <typename T>
auto CreateObjectWithKey();

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

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

那么你可以如下使用它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2012-07-02
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多