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

templates – 带有函数调用表达式的`decltype`何时需要定义函数

发布时间:2020-12-16 07:07:59 所属栏目:百科 来源:网络整理
导读:在clang我得到这个警告 warning: inline function 'detail::selector2,int::select' is not defined [-Wundefined-inline] static constexpr auto select(T const) - std::integral_constantint,Which; ^note: used herestatic_assert( decltype(Selector::s
在clang我得到这个警告

warning: inline function 'detail::selector<2,int>::select' is not defined [-Wundefined-inline]
    static constexpr auto select(T const&) -> std::integral_constant<int,Which>;
                          ^

note: used here
static_assert( decltype(Selector::select(int()))::value == 2,"");
                                  ^

在下面的代码中.

是不是在这里定义了有害的功能? (我坚信,在我的应用程序中并不重要,因为它在未评估的上下文中使用,在std :: enable_if中).

现在,我想知道编译器何时会发出警告.

#include <type_traits>

namespace detail {

    template <int Which,typename...> struct selector;

    template <int Which>
    struct selector<Which> {
        static constexpr void select();  // never select
    };

    template <int Which,typename T,typename... Ts>
    struct selector<Which,T,Ts...> : selector<Which+1,Ts...>
    {
        using selector<Which+1,Ts...>::select;
        static constexpr auto select(T const&) -> std::integral_constant<int,Which>;
    };
}

int main(int argc,const char * argv[])
{
    using Selector = detail::selector<0,char,short,int>;
    static_assert( decltype(Selector::select(int()))::value == 2,"");    
    return 0;
}

编辑:

笔记:

> ideone.com上的gcc-4.8.1不会发出警告.
>摆脱警告的最简单方法是提供一种实现,例如:

static constexpr auto select(T const&) 
-> std::integral_constant<int,Which> 
{ return {}; }

(谢谢@Yakk)

解:

正如@Filip Roséen提供的答案中所解释的那样,constexpr说明符将隐式声明该函数内联,这需要在评估时定义.但是我的代码中没有使用该函数 – 但是仍然会发出警告(表示编译器中的一个小问题).当省略constexpr说明符时,clang将不再发出此警告.无论如何,constexpr说明符似乎不合适(谢谢@Yakk).

解决方法

注意;如上所述,clang发出的诊断仅仅是一个警告,而不是一个错误,这意味着它只是吸引我们注意一个如果处理不当可能会被误用的段.

什么可能会出错?

标记为constexpr的实体是隐式内联的(对于直接在类中定义的函数也是如此),如[dcl.fct.spec] p3中所述.

具有内联说明符的函数,无论是否隐式,都必须遵循应用于此类的规则. clang发出的警告是为了警告开发人员编写违反以下内容的代码(其中包括):

[dcl.fct.spec]

4) An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2).

[basic.def.odr]

2) An expression is potentially evaluated unless it is an unevaluated operand (Clause 5) …

3) A variable x whose name appears as a potentially-evaluated expression ex is odr-used

4) … An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2).

clang是否正确在我们的上下文中发出-Wundefined-inline?

技术上……不,警告没有任何价值,因为我们使用select不会违反未评估上下文中的一个定义规则.

你可以通过在调用clang时传递-Wno-undefined -inline来抑制警告,如果这让你很困扰,请file a bug report.

(编辑:李大同)

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

    推荐文章
      热点阅读