使用SFINAE检查函数是否为constexpr

问题描述

我想检查在编译过程中是否可以评估函数。我找到了this,但我并不完全理解这个概念。我有一些疑问:

  1. 以下行在代码中的作用是什么?
    template<int Value = Trait::f()>

  2. 每当需要检查该函数是否可在编译时求值时,是否需要使其成为某个结构的成员函数

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;
};

Demo here