如何确定 C 11 成员函数的返回类型

新手上路,请多包涵

我正在尝试确定各种 C++ 成员函数的返回类型。我知道可以使用 decltype 和 std::declval 来执行此操作,但是我遇到了语法问题并找到了有用的示例。下面的 TestCBClass 显示了一个哑类的示例,该类包含静态和普通成员函数的混合 - 带有 & 不带参数和返回类型。根据所讨论的方法,我希望能够从每种方法中声明一个返回类型的向量。

在我的应用程序中,这些方法是 std::async 的回调,我需要一个 std::future<return types> 的向量。我尝试了各种声明,例如 decltype(std::declval(TestCBClass::testStaticMethod)) (我不确定在方法名称之前是否需要 & )。这种语法是不正确的——当然它不能编译,但我认为它应该使用这种方法。

 class TestCBClass {
public:
    TestCBClass(const int& rValue = 1)
        : mValue(rValue) {
        std::cout << "~TestCBClass()" << std::endl;
    }
    virtual ~TestCBClass() {
        std::cout << "~TestCBClass()" << std::endl;
    }
    void testCBEmpty(void) {
        std::cout << "testCBEmpty()" << std::endl;
    }
    int testCBArgRet(const int& rArg) {
        std::cout << "testCBArgRet(" << rArg << ")" << std::endl;
        mValue = rArg;
    }
    static void testCBEmptyStatic(void) {
        std::cout << "testCBEmptyStatic()" << std::endl;
    }
    static void cbArgRetStatic(const SLDBConfigParams& rParams) {
        std::lock_guard<std::mutex> lock(gMutexGuard);
        std::cout << rParams.mPriority << std::endl;
    }
    static std::string testStaticMethod(const PriorityLevel& rPrty) {
        return "this is a silly return string";
    }
private:
    int mValue;
};

原文由 johnco3 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 750
2 个回答

您也可以使用 std::result_ofdecltype ,如果您更喜欢列出参数类型而不是相应的虚拟值,如下所示:

 #include <iostream>
#include <utility>
#include <type_traits>

struct foo {
  int    memfun1(int a) const { return a;   }
  double memfun2(double b) const { return b; }
};

int main() {
  std::result_of<decltype(&foo::memfun1)(foo, int)>::type i = 10;
  std::cout << i << std::endl;
  std::result_of<decltype(&foo::memfun2)(foo, double)>::type d = 12.9;
  std::cout << d << std::endl;
}

演示在这里。

原文由 Krizz 发布,翻译遵循 CC BY-SA 3.0 许可协议

如何确定 C++11 成员函数的返回类型?

回答:

您可以使用 decltypestd::declval 就像下面的玩具示例:

 #include <iostream>
#include <utility>

struct foo {
  int    memfun1(int a) const { return a;   }
  double memfun2(double b) const { return b; }
};

int main() {
  decltype(std::declval<foo>().memfun1(1)) i = 10;
  std::cout << i << std::endl;
  decltype(std::declval<foo>().memfun2(10.0)) d = 12.9;
  std::cout << d << std::endl;
}

现场演示

原文由 101010 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题