std::experimental::source_location
将来可能会被添加到C++标准中。我想知道是否可能将位置信息传递到编译时领域。本质上,当从不同的源位置调用时,我想要一个返回不同类型的函数。像这样的一些东西,尽管它不能编译,因为location对象不是
constexpr
作为函数参数:
#include <experimental/source_location>
using namespace std::experimental;
constexpr auto line (const source_location& location = source_location::current())
{
return std::integral_constant<int, location.line()>{};
}
int main()
{
constexpr auto ll = line();
std::cout << ll.value << '\n';
}
这段代码无法编译,会提示相关错误信息
expansion of [...] is not a constant expression
关于return std::integral_constant<int, location.line()>{}
这一行。如果我无法使用source_location
的方法,那么它们是constexpr
有什么好处呢?
std::experimental::source_location
没有任何关系。line
函数是constexpr
的,但它的参数不是constexpr
的。函数参数从来都不是constexpr
的。在C++20中,我们可以将任意类型作为模板参数,因此source_location
可能是一个模板参数。 - Justinsource_location
对象的后期构建的唯一方法是使用默认函数参数。默认的模板参数不起作用;它是早期创建的,而不是晚期。这可能是一个疏忽。constexpr
函数参数可以解决问题,但目前这个想法并不太受欢迎。 - Justin