如何检查模板类方法返回类型
How to check template class method return type?
我尝试在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())
相关文章:
- 从父类方法返回子类对象
- 我的模板类方法返回错误类型?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 我无法使用C++指针指向类方法返回的 std::vector
- 类方法返回指向具有模板的类成员的指针
- 从类方法返回 "const char*" 作为 std::string&
- qml 未知方法返回类型:ArchiveFile*,即使调用了 qmlRegisterUncreatableType
- std::d eclval vs crtp,无法从不完整类型推断方法返回类型
- 从基类方法返回对派生类的引用
- dlsym() 解决方法返回类型
- 使用 enable_if 专门处理基类的返回类型
- 如何打印通过类方法返回的值
- 如何检查模板类方法返回类型
- 如何<double>从基于 QObject 的类方法返回 QList 以在 Qt 脚本中使用
- 覆盖方法返回类型,在C 中使用不完整的派生类
- 如何从模板化的类方法返回依赖类型
- C++类方法返回不同的类型
- 类成员方法 - 返回类型模板
- C++中具有多态模板类的未知方法返回类型
- 使用不同方法返回类型的C++模板类设计