如何解决使用SFINAE检查函数是否为constexpr
我想检查在编译过程中是否可以评估函数。我找到了this,但我并不完全理解这个概念。我有一些疑问:
-
以下行在代码中的作用是什么?
template<int Value = Trait::f()>
-
每当需要检查该函数是否可在编译时求值时,是否需要使其成为某个结构的成员函数?
PS
为了方便起见,我正在复制链接中的代码。
template<typename Trait>
struct test
{
template<int Value = Trait::f()>
static std::true_type do_call(int){ return std::true_type(); }
static std::false_type do_call(...){ return std::false_type(); }
static bool call(){ return do_call(0); }
};
struct trait
{
static int f(){ return 15; }
};
struct ctrait
{
static constexpr int f(){ return 20; }
};
int main()
{
std::cout << "regular: " << test<trait>::call() << std::endl;
std::cout << "constexpr: " << test<ctrait>::call() << std::endl;
}
解决方法
这里仅是一个简单的示例,说明您可以使用std::void_t
来解决您的第2点,这在某种程度上是通用的...
#include <iostream>
#include <type_traits>
int f() {
return 666;
}
constexpr int cf(int,double) {
return 999;
}
template <auto F>
struct indirection {
};
template<typename F,class = std::void_t<> >
struct is_constexpr : std::false_type { };
template<typename F,typename... Args>
struct is_constexpr<F(Args...),std::void_t<indirection<F(Args{}...)>>
> : std::true_type { };
int main()
{
std::cout << is_constexpr<decltype(f)>::value << std::endl;
std::cout << is_constexpr<decltype(cf)>::value << std::endl;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。