【问题标题】:How to implement std::result_of with only c++98 features?如何仅使用 c++98 功能实现 std::result_of?
【发布时间】:2017-07-13 08:34:52
【问题描述】:

我想知道如何实现一个result_of模板类来获取函数的返回类型。

我知道 C++11 有 std::result_of 或 decltype。但是 boost 是如何在 C++98 标准中实现这个特性的呢?

我尝试从源代码中学习,但我没有明白这一点。

应该是这样的:

int fint() { return 0;}
double fdouble() { return double(0);}
cout << sizeof(result_of<fint>::type) << endl; // should be 4
cout << sizeof(result_of<fdouble>::type) << endl; // should be 8
result_of<fint>::type x; // same as `int x;`
result_of<fdouble>::type y; // same as `double y;`

【问题讨论】:

  • @tobi303 是的,我已经更正了
  • 专门针对Ret (*) (T1, ...,TN) 到一些N
  • 这是一个有趣的问题,但您已经知道答案:boost 实现了它。恕我直言,如果你在 boost 代码上说出你不理解的东西会更好,因为我怀疑有人会想出比 boost 更简单的东西
  • 我不知道哪里错了,但是代码就是无法编译......

标签: c++ templates boost metaprogramming c++98


【解决方案1】:

专门针对Ret (*) (T1, ...,TN) 到一些N

template <typename T> struct result_of;

template <typename Ret> struct result_of<Ret (*)()> {
    typedef Ret type;
};

template <typename Ret, typename T1> struct result_of<Ret (*)(T1)> {
    typedef Ret type;
};

template <typename Ret, typename T1>
struct result_of<Ret (*)(T1, ...)> { /* ellipsis as for printf */
    typedef Ret type;
};

template <typename Ret, typename T1, typename T2> struct result_of<Ret (*)(T1, T2)> {
    typedef Ret type;
};

// ...

【讨论】:

  • result_of.cpp:71:15: 错误:'float f_f()' 不能出现在常量表达式 result_of::type a = 3; ^ result_of.cpp:71:19: 错误:函数调用不能出现在常量表达式 result_of::type a = 3;
  • 我无法将函数调用传递给模板参数。它不是在编译时定义的。
  • @LiuWeibo f_f() 不是函数,但f_f
  • result_of.cpp:在函数'int main()'中:result_of.cpp:71:18:错误:'template 结构的模板参数列表中参数 1 的类型/值不匹配result_of' result_of::type a = 3;
  • @PasserBy: 如果函数重载,获取结果类型无论如何可能是不明确的 ;-) (仍然可以转换为正确的类型,但是,我们不必输入函数 ;-) )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多