如何检查模板类方法返回类型

How to check template class method return type?

本文关键字:类方法 返回类型 检查 何检查      更新时间:2023-10-16

我尝试在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())>;

使用std::declval

template <class T, class U>
struct hasProperMethodReturnValueType
  : std::is_same<T, decltype(std::declval<U>().getGG())>
{};

https://wandbox.org/permlink/iwucoyssn3svo2yh

std::decltype(U.getGG())中,U是一种类型,而getGG是成员函数。U.getGG()只是无效的语法 - 您需要"创建" U的实例来调用成员函数-std::declval是在未评估的上下文中为您做到这一点的实用程序。也不存在std::decltype -decltype是关键字。

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