我想问题的标题没有多大意义,但我希望问题描述能传播开来。
有人可以解释一下这到底是如何通过编译的吗?
template<typename Cont, typename = std::enable_if<std::is_integral_v<std::string>>>
void print(const Cont& cont)
{
for (const auto it : cont) {
cout << it << " ";
}
cout << endl;
}
int main()
{
std::vector<string> V;
print(V);
}
原来的版本是:template<typename Cont, typename = std::enable_if<std::is_integral_v<typename Cont::value_type>>>
我只是明确地把 std::string 确定了。我猜 enable_if 应该禁止这个函数被实例化吧?
我在这里想念什么?
最佳答案
std::enable_if<false>
仍然作为一种类型存在,这就是您推断出未使用的类型参数的原因。
它只是作为一种本身没有嵌套公共(public)成员 typedef type
的类型存在。 .这就是为什么你必须使用 std::enable_if<EXPR>::type
或 std::enable_if_t<EXPR>
得到你期望的行为。
您可以在 the documentation 中查看您的用例示例。 .
只是为了完整性:
Why is_integral_v is true?
不是!你只是没有检查你以为你是什么。
将来,当您遇到这样的事情时(当您知道要写什么时,很难看出哪里出了问题),请尝试寻找另一种方法来测试您的假设。你可以打印
is_integral_v<std::string>
看看它是真的还是假的。或者,当然,让别人看看。其他人通常可以立即看到我们的大脑有助于过滤掉的错误。
关于c++ - 为什么 is_integral_v<string> 是真的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63455928/