我最近就想知道这个问题。gcc 等编译器如何在编译时实现 constexpr 函数调用的求值?
最方便的方法似乎是使用函数的编译机器代码或更可能是一些编译中间代码并执行它,但这有一些问题。在 2020 年,constexpr 函数中允许标准动态分配。如果 constexpr 函数有一些错误编写的内存管理代码并尝试双重释放指针怎么办?如果编译器在这种情况下不崩溃就更好了。如果它破坏堆栈并覆盖编译器进程中其他地方的数据怎么办?同样,如果编译器不崩溃就更好了。编译器是否在沙箱环境中执行它?它如何检测此类内存错误?如果发生这样的内存错误怎么办?编译器是否会以其他方式模拟该函数?谢谢。
我最近发现类模板的成员函数在使用之前不会被实例化,这非常烦人,因为它使某些SFINAE结构不起作用.我想知道如何确保在实例化类之后始终实例化类模板特化的成员函数 - 但仅使用类模板定义中的语句,以便在成员函数无法实例化时,SFINAE启动并且编译器回退到通用类模板.
我打算使用的代码如下所示:
template <typename T, typename U>
class test_type {
// general template; dummy parameter U is to allow specialization.
static const bool value = false;
}
template <typename T>
class test_type<T, T> {
// template specialization
void f(T t) {
// do all sorts of type-specific operations with t
// (e.g., calling member functions)
// if T is not suitable for these operations, I want
// a substitution error to be generated so that the
// general …Run Code Online (Sandbox Code Playgroud)