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

标签 c++ templates template-specialization

下面的代码片段演示了我想要实现的目标,即创建两个模板特化(好吧,这里是一个主模板和一个特化),一个将用于非 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), &foo::bar> bar_type;

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

关于c++ - 如何重写它以使其符合 C++ 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15192700/

相关文章:

c++ - 使用模板特化来比较指针引用

c++ - 可变参数模板的模板特化

c++ - gSOAP C++ 多线程独立服务器和客户端示例

c++ - 对角排列数组

php - PHP 中的超轻型模板系统,不允许模板内的 php 代码或使用 eval

django - Django:如何从模板调用 View 函数?

c++ - 读取表达式

c++ - 删除 ptr C++ 后会发生什么

c++ - 非模板类中模板方法中的dll和静态变量

c++ - 如何专门化类模板的静态函数?