【发布时间】: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