假设我们使用C++17的
概念的文档资料很少,所以我可能理解错了,但似乎就是这样(而且有一个实时示例在Wandbox上)。
现在让我们考虑取消注释另一个
这是gcc的一个bug,还是这是预期的行为?
if constexpr
和Concepts TS(例如,在最新的gcc版本中),我们想要检查模板函数中的类型是否有嵌套类型。#include <iostream>
struct Foo { using Bar = int; };
template<typename T>
void doSmth(T)
{
if constexpr (requires { typename T::Bar; })
std::cout << "has nested! " << typename T::Bar {} << std::endl;
else
std::cout << "no nested!" << std::endl;
}
int main()
{
doSmth(Foo {});
//doSmth(0);
}
概念的文档资料很少,所以我可能理解错了,但似乎就是这样(而且有一个实时示例在Wandbox上)。
现在让我们考虑取消注释另一个
doSmth
调用时应该发生什么。合理的期望是要求子句将评估为false
,并且if constexpr
的else
分支将被执行。然而,与此相反,gcc将此视为严重错误。prog.cc: In instantiation of 'void doSmth(T) [with T = int]':
prog.cc:17:13: required from here
prog.cc:8:5: error: 'int' is not a class, struct, or union type
if constexpr (requires { typename T::Bar; })
^~
这是gcc的一个bug,还是这是预期的行为?
requires
子句的使用范围。允许这样做已经在P0266中单独提出。我认为我们还无法回答你的问题。 - Rakete1111requires { requires std::is_same_v<T, int> }
的语法在这个上下文中能够正常工作(我对这种语法还不是很熟悉,所以可能写错了)。 - 0xd34df00d