【问题标题】:specialization on const member function pointersconst成员函数指针的特化
【发布时间】:2010-12-26 02:30:52
【问题描述】:

我正在尝试将一些实用程序代码专门用于 const 成员函数,但在让一个简单的测试用例工作时遇到问题。
为了简化工作,我正在使用 Boost.FunctionTypes 及其 components<FunctionType> 模板 - 一个 MPL 序列 应该 contain 标签 const_qualified 用于 const 成员函数。

但是使用下面的测试代码,const 成员函数的特化失败了。有人知道如何让它工作吗?

测试代码打印出来(使用 VC8 和 boost 1.40):

非常量
非常量

预期输出是:

非常量
常量

测试代码本身:

#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/mpl/contains.hpp>

namespace ft  = boost::function_types;
namespace mpl = boost::mpl;

template<typename F>
struct select 
{    
    template<bool IsConst /* =false */>
    struct helper {
        static void f() { std::cout << "non-const" << std::endl; }  
    };

    template<>
    struct helper</* IsConst= */ true> {
        static void f() { std::cout << "const" << std::endl; }  
    };

    typedef ft::components<F> components;
    typedef typename mpl::contains<components, ft::const_qualified>::type const_qualified;
    typedef helper<const_qualified::value> result;
};

typedef boost::function<void (void)> Functor;

template<typename MF>
Functor f(MF f)
{
    return boost::bind(&select<MF>::result::f);
}

class C 
{
public:
    void f1() {}
    void f2() const {}
};

int main()
{
    f(&C::f1)(); // prints "non-const" as expected
    f(&C::f2)(); // prints "non-const", expected "const"
}

【问题讨论】:

  • 虽然我找到了另一种方法,但我仍然很乐意接受针对原始问题的经过测试的解决方案。

标签: c++ templates boost specialization member-function-pointers


【解决方案1】:

虽然我仍然不清楚为什么通过 function_types::components&lt;&gt; 的方法不起作用,但我意识到 Boost.FunctionTypes 有一种更简单的方法可以专注于 const 成员函数:
is_member_function_pointer&lt;&gt; 之类的分类元函数可选地采用 tag 参数 ...

template<typename F>
struct select 
{    
    /* ... helper-struct as before */

    typedef ft::is_member_function_pointer<F, ft::const_qualified> const_qualified;
    typedef helper<const_qualified::value> result;
};

【讨论】:

    【解决方案2】:

    我没有测试过,但不应该

    typedef mpl::contains<components, ft::const_qualified> const_qualified;
    

    成为

    typedef typename mpl::contains<components::type, ft::const_qualified>::type const_qualified;
    

    【讨论】:

    • 我在那里看到了你的编辑,但是你的组件 typedef 也需要 ::type 或者像我在帖子中所做的那样。
    • ::type 就像调用元函数并获取结果一样。如果你不这样做,它会使用元函数本身。
    • 也没什么区别。
    猜你喜欢
    • 2016-08-17
    • 2011-03-04
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多