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

如何重写它以使其符合C标准

发布时间:2020-12-16 09:42:54 所属栏目:百科 来源:网络整理
导读:下面的代码片段演示了我想要实现的内容,即创建两个模板特化(嗯,这里是主模板和特化),一个用于非const成员函数,一个用于const成员函数: // instantiate for non-const member functionstemplate typename C,void(C::*F)()struct A {};// instantiate for con
下面的代码片段演示了我想要实现的内容,即创建两个模板特化(嗯,这里是主模板和特化),一个用于非const成员函数,一个用于const成员函数:

// instantiate for non-const member functions
template <typename C,void(C::*F)()>
struct A {};

// instantiate for const member functions
template <typename C,void(C::*F)() const>
struct A<C const,F> {};

struct foo
{
    void bar() const {}
    typedef A<foo const,&foo::bar> bar_type;

    void baz() {}
    typedef A<foo,&foo::baz> baz_type;
};

虽然此代码使用gcc 4.7,Intel 13.0和MSVC 2012编译得很好,但它无法使用Clang 3.3或Comeau 4.3.10.1进行编译.我相信Clang实际上是对的.

如何重写此代码以使其符合标准(即使用Clang进行编译)?

这是编译错误:

test_6.cpp:22:26: error: non-type template argument of type 'void (foo::*)() const' cannot be converted to a value of type 'void (const foo::*)()'
    typedef A<foo const,&foo::bar> bar_type;
                         ^~~~~~~~~
test_6.cpp:7:33: note: template parameter is declared here
template <typename C,void (C::*F)()>
                                ^

解决方法

如果使成员函数键入模板参数,则可以为不同的成员函数类型专门化模板:

template <typename C,typename F,F>
struct A;  // undefined

template <typename C,void(C::*f)()>
struct A<C,void(C::*)(),f> {};

template <typename C,void(C::*f)() const>
struct A<C const,void(C::*)() const,f> {};

struct foo
{
    void bar() const {}
    typedef A<foo const,decltype(&foo::bar),decltype(&foo::baz),&foo::baz> baz_type;
};

(编辑:李大同)

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

    推荐文章
      热点阅读