给出以下代码:
#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/