2017-11-25 126 views
0

我嘗試檢查Class2的方法getGG()作爲模板參數給出的返回值類型,但我的代碼不能編譯。如何正確地做到這一點?如何查看模板類的方法返回類型?

template <class T, class U> 
struct hasProperMethodReturnValueType { 
    static constexpr bool value = std::is_same<T, std::decltype(U.getGG())>; 
}; 

template<class P> class Class1 { 
private: 
    P gg; 
public: 
    Class1(P a) : gg(a) {} 
    P getGG() { 
     return gg; 
    } 
}; 

template<class A, class P> class Class3 { 
private: 
    P gg; 
    A dd; 
public: 
    Class3(P a, A r) : gg(a), dd(r) {} 
    P getGG() { 
     return gg; 
    } 
}; 

template<class G, class R> class Class2 { 
    static_assert(hasProperMethodReturnValueType<G, R>::value, "Not same type"); 
private: 
    R cc; 
public: 
    Class2(R r) : cc(r) {}; 
}; 

int main() { 
    auto obj = Class2<int, Class1<int> >(Class1<int>(3)); 
    auto obj2 = Class2<int, Class3<float, int> >(Class3<float, int>(0, 1.1)); 
    return 0; 
} 

編譯錯誤:

error: template argument 2 is invalid 
    static constexpr bool value = std::is_same<T, std::decltype(U.getGG())>; 
+4

這是'decltype',沒有'的std :: decltype'。這是一種語言功能。 – DeiDei

回答

1

std::decltype(U.getGG())U是一種類型,而getGG是一個成員函數。 U.getGG()簡直是無效的語法 - 您需要「創建」一個U的實例來調用成員函數 - std::declval是一個實用程序,可以在未評估的上下文中爲您執行此操作。 std::decltype不存在 - decltype是一個關鍵字。

decltype(std::declval<U>().getGG())