C++ 模板类型检查 std::is_same 不起作用?

标签 c++ templates visual-c++

给出以下代码:

#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 并因此抛出编译器错误。这背后的常识是什么?或者换句话说,检查模板类型的正确原因是什么。

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

提前致谢!

最佳答案

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

要解决此问题,您需要 C++17 中的 constexpr if,或者在以前的版本中使用标记分派(dispatch)或 SFINAE。

关于C++ 模板类型检查 std::is_same 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879457/

相关文章:

c++ - 使用 `void_t` 检查类是否具有具有特定签名的方法

c++ - 是否可以修复 Windows 头文件(winnt.h、windefs.h)以便它们可以用/Za 编译?

c++ - 在派生类中更改虚函数的参数是什么意思?

C++如何泛化类函数参数来处理多种类型的函数指针?

c++ - 如何在 C++ 中简化这个 "variable as template parameter"?

windows - 我如何从 C++ 服务应用程序访问 Windows 登录(身份验证)API?

c++ - VisualC 2010、项目引用和包含路径

C++对象内存消耗

c++ - 比较 if 语句中的 int 值

C++重载