4

我想在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" 
} 
+0

雖然我找到了另一種方法,我還是很樂意接受一個測試解決原來的問題。 – 2009-12-13 08:15:25

回答

1

雖然它仍不清楚我爲什麼方法通過function_types::components<>不起作用,我意識到有一個更簡單的方法與Boost.FunctionTypes sp ecialize在const成員函數:像is_member_function_pointer<>
分類元功能可選採取標籤參數...

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; 
}; 
0

我沒有測試過,但不應

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

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

已經嘗試過,沒有什麼區別。 – 2009-12-13 07:36:08

+0

我在那裏看到了你的編輯,但是你的組件typedef也需要:: type或者像我在帖子中所做的那樣。 – leiz 2009-12-13 07:44:39

+0

::類型就像調用元函數並獲得結果。如果你不這樣做,它使用元函數本身。 – leiz 2009-12-13 07:47:21