2016-11-04 28 views
1

有沒有一種方法,如何在std::declval<T>()之後傳遞方法名稱作爲模板參數?C++ 11 - std :: declval <T>()方法的名稱

到目前爲止,我有這樣的:

template<typename T, typename ... Args> 
struct MethodInfo 
{ 
    using type = decltype(std::declval<T>().foo(std::declval<Args>() ...)) (T::*)(Args ...); 
}; 

但是我想 「foo」 爲模板parametr。

+0

不完全符合您的要求,但會像[this](http://coliru.stacked-crooked.com/a/0197cd774882606c)滿足您的需求? – TartanLlama

+0

@TartanLlama不,因爲這不適用於重載的方法 –

回答

1

這不正是你問什麼,但我覺得這可能有些適合你的需要:

#include <type_traits> 
#include <tuple> 
#include <iostream> 

template<typename T, typename... Args> 
struct MethodInfo { 
    template<typename Ret> 
    static auto get(Ret(T::*)(Args...)) -> Ret(T::*)(Args...); 
}; 

struct Foo { 
    int foo(int); 
    int foo(int, int); 
}; 

int main() { 
    static_assert(std::is_same< 
         int(Foo::*)(int), 
         decltype(MethodInfo<Foo, int>::get(&Foo::foo)) 
          >::value, ""); 
} 

Demo

因爲函數名是一個非類型的模板參數,我認爲這是唯一的解決方案,直到現在。

+0

這不是我問的問題,但這個解決方案比我的更好......它正在工作,我設法將它包裝到預處理器宏中,所以代碼很短 –

1

在C++ 11你能做到這一點,但它幾乎擊敗這個類的目的:

template<typename T, typename U, U ptr, typename... Args> 
struct TypeOverload; 

template<typename T, typename U, typename... Args, U(T::* ptr)(Args...)> 
struct TypeOverload<T, U(T::*)(Args...), ptr, Args...> 
{ 
    using type = decltype((std::declval<T>().*ptr)(std::declval<Args>() ...)) (T::*)(Args ...); 
}; 

因爲使用情況如下:

using bar_t = TypeOverload<Foo, decltype(&Foo::bar), &Foo::bar, int, int>::type; 
static_assert(std::is_same<bar_t, void(Foo::*)(int,int)>::value, ""); 

demo


但用auto模板參數在C++ 17中,你可能有t他:

template<typename T, auto ptr, typename... Args> 
struct TypeOverload 
{ 
    using type = decltype((std::declval<T>().*ptr)(std::declval<Args>() ...)) (T::*)(Args ...); 
}; 

,你會按如下方式使用它:

using bar_t = TypeOverload<Foo, &Foo::bar, int, int>::type; 
static_assert(std::is_same<bar_t, void(Foo::*)(int,int)>::value, ""); 

demo

+0

@TartanLlama對,我從錯誤的窗口複製過來。話雖如此,我只是讀了OP關於重載的評論,所以這個答案可能需要被刪除。 – krzaq

+1

我不確定是否真的需要負責重載,因爲您需要在調用站點調用'static_cast'來消除歧義。我猜'foo'可能是一個帶有模板/重載操作符(')的成員函子?這是我能想到的唯一方法。 – TartanLlama

+0

@krzaq它可以處理現場演示中的重載。但是,在Visual Studio 2015中,它不會編譯:/ - ''TypeOverload':模板參數'Args'與聲明不兼容''TypeOverload':太多的模板參數' –