constexpr函数模板何时实例化?

Ben*_*uch 11 c++ templates instantiation constexpr

我正在制定一个提出功能头功能的提议constexpr.(std::invoke,std::reference_wrapper,std::bind,std::mem_fn,std::not_fn)

我已经了解到添加constexpr可以破坏现有代码,因为constexpr函数是急切实例化的.

template<class T>
int f(T){
    return T::not_existing_member;
}

template<class T>
constexpr int g(T){
    return T::not_existing_member;
}

int main(){
    decltype(f(0)) a; // Well-formed
    decltype(g(0)) b; // Ill-formed if the function body is instantiated
}
Run Code Online (Sandbox Code Playgroud)

GCC编译这段代码,clang没有.我在我的提议中描述了如何使用示例来处理带有重载的急切实例化std::bind.

你能告诉我编译器必须在标准中描述的位置,以及何时允许实例化一个功能模板?

更确切地说,我想知道在以下示例中,GCC和clang的相同行为是由标准强制执行还是实现定义:

template<class T>
struct Foo{
    constexpr int f(){
        return 0;
    }

    constexpr int f()const{
        return T::not_existing_member;
    }
};

int main(){
    /* constexpr */ Foo<int> foo;
    foo.f(); // Ill-formed with, Well-formed without constexpr by the standard?
}
Run Code Online (Sandbox Code Playgroud)

如果foo不是constexpr,GCC和clang都会编译代码,如果是,则拒绝它.

Bar*_*rry 6

示例#1是活动的CWG问题1581.目前尚未完全指定正确的行为应该是什么.方向似乎是constexpr实例化应该是急切的,但这需要在未来的某个时候澄清.

示例#2很简单:调用格式int Foo<int>::f() const不正确.当你的foo对象const出现时,会发生这种情况const.类模板的成员函数仅在使用时被实例化,如果您的Foo<int>对象是非对象const,我们永远不会实例化const成员函数,因此代码格式正确.constexpr与此无关.