加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:26:43 所属栏目:百科 来源:网络整理
导读:我正在努力使函数头函数constexpr. (std :: invoke,std :: reference_wrapper,std :: bind,std :: mem_fn,std :: not_fn) Preview of the proposal 我了解到,添加constexpr可以破坏现有的代码,因为constexpr函数被实例化. templateclass Tint f(T){ return T
我正在努力使函数头函数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在这里是不相关的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读