微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 什么时候实现constexpr函数模板?

我正在努力使函数函数constexpr. (std :: invoke,std :: reference_wrapper,std :: bind,std :: mem_fn,std :: not_fn)

> Preview of the proposal

我了解到,添加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
}

GCC编译这段代码,cl ang不行.我在my proposal中描述了如何使用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?
}

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

解决方法

示例#1是活动的 CWG issue 1581.目前没有完全指定正确的行为应该是什么.方向似乎是constexpr的实例化应该是渴望的,但是这需要在将来的某个时候加以澄清.

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

原文地址:https://www.jb51.cc/c/114789.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐