C++ 模板类型检查 std::is_same 不起作用? [英] C++ Template type check std::is_same not working?

查看:46
本文介绍了C++ 模板类型检查 std::is_same 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

#include <string>

template<typename T>
static void parse(T & result)
{
    if (std::is_same<T, struct Foo>::value)
    {
        result.fooValue = 123;
    }
    else if (std::is_same<T, struct Bar>::value)
    {
        result.barValue = 456;
    }
}

struct Foo { int fooValue; };
struct Bar { int barValue; };

int main()
{
    Foo foo;
    parse(foo);

    Bar bar;
    parse(bar);

    return 0;
}

这不会编译错误消息:

error C2039: 'barValue': is not a member of 'Foo'
error C2039: 'fooValue': is not a member of 'Bar'

我做错了什么?有人可以向我解释为什么当我将 foo 传递到 parse 并传递 bar 后,它认为它是 foo因此抛出编译器错误.这背后的常识是什么?或者换句话说,检查模板类型的正确原因是什么.

What am I doing wrong? can someone please explain to me why when after I pass foo into parse and passing bar it thinks that it's foo and therefore throwing compiler errors. What's the common sense behind this? or in other words, what's the proper why of checking the template type.

请注意,我已经了解模板特化和实例化.

Note that I already know about template specialization and instantiation.

提前致谢!

推荐答案

模板实例化时,两个分支都需要编译.显然,其中一个不能 - 特定模板类型只有一个成员,而没有另一个.

When template is instantiated, both branches need to be compiled. Obviously, one of them can't - the specific template type has only one member, but not another.

要解决这个问题,您需要来自 C++17 的 constexpr if,或者,在以前的版本中,使用标签调度或 SFINAE.

To solve this problem, you would either need constexpr if from C++17, or, with previous versions, use tag dispatch or SFINAE.

这篇关于C++ 模板类型检查 std::is_same 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆