2016-08-22 54 views
4

我想在C++ 11(msvc2013)中編寫一個類型特徵,這將允許我檢查函數類型是否需要某些參數。我不要希望它檢查返回類型。我認爲這個想法基本上等於std::is_callable,但我很想知道我的方法有什麼問題,除了如何真正解決問題。trait檢查函數接受某些參數,但不返回類型

我的實現:

namespace traits 
{ 
    namespace detail 
    { 
     template <typename T> 
     struct is_write_function_impl 
     { 
      const char* c = nullptr; 
      size_t l = 0; 

      template<typename U> 
      static auto test(U*)->decltype(declval<U>()(c, l), std::true_type); 
      template<typename U> 
      static auto test(...)->std::false_type; 

      using type = decltype(test<T>(0)); 
     }; 
    } 

    template <typename T> 
    struct is_write_function : detail::is_write_function_impl<T>::type {}; 
} 

我的測試用例:

std::ofstream os; 
auto valid = std::bind(&std::ofstream::write, &os, 
    std::placeholders::_1, std::placeholders::_2); 

// want this to be 'true' but get 'false' 
std::cout << traits::is_write_function<decltype(valid)>::value; 
+0

我聽說VS 2013不支持表達式SFINAE,所以它可能無法在VS 2013中實現。 – cpplearner

+0

@cpplearner不知道它是否是蘋果和桔子,但我使用這個基本模式來檢查類的靜態成員函數所有的時間在2013年。我只是無法適應功能對象。 –

回答

5

有相當多的問題,這將通過更好的編譯器檢測到) - 但是如果你解決這些問題,你的代碼

static auto test(U*)->decltype(declval<U>()(c, l), std::true_type); 
           #1   #2  #3 
    :將與VS 2013工作(與12.0.31101.00更新4測試) 0
  1. 這應該是std::declval
  2. 即使在未推導的上下文中,您也不能在static成員函數聲明中引用非static數據成員。這應該是(std::declval<char const*>(), std::declval<std::size_t>())
  3. std::true_type是一種類型,並且decltype是表達式上下文。寫std::true_type{}

Example

+0

誰需要一個更好的編譯器與這樣的質量幫助? :) –

相關問題