我想在const成員函數上專門化一些實用程序代碼,但有問題需要簡單的測試用例才能工作。
爲了簡化我正在利用Boost.FunctionTypes及其components<FunctionType>
模板的工作 - 一個MPL序列應該contain
爲const成員函數標籤const_qualified
。關於const成員函數指針的專門化
但是使用下面的測試代碼,const成員函數的特化失敗。有人知道如何使其工作?
測試碼打印出(使用VC8和升壓1.40):
非const
非const
預期輸出是:
非const
const
測試代碼本身:
#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"
}
雖然我找到了另一種方法,我還是很樂意接受一個測試解決原來的問題。 – 2009-12-13 08:15:25