繁体   English   中英

在VS2010中获取可调用类型的返回类型

[英]Getting Return Type of Callable Type in VS2010

我有一个带有可调用类型参数<typename Callable>的模板类。

我知道Callable确实创建了一个可调用对象,并且通常是一个lambda。
在我的特定情况下,我也知道参数的数量(arity)和类型(只有一个)。

如何在VS2010上获得此可调用类型Callable的返回类型?

请参见std::result_of

假装使用一个int参数调用该对象,您可以执行以下操作:

using return_type = typename std::result_of<Callable(int)>::type;

这通常是不可能的。

有多种方法可以使用可调用类型,包括lambdas和重载operator() struct

C ++几乎没有像C#那样的语言反射类型,而且C ++提供的工具也无法做到。

如果您只想将“callable”的结果存储到变量中,那么您可以使用auto

如果你真的想根据它的类型对结果做一些事情,那么这个问题可能有所帮助。

基本上,将其添加到您的代码中。

template <typename T, typename U>
struct same_type 
{
   static const bool value = false;
};
template <typename T>
struct same_type< T, T >
{
   static const bool value = true;
};

然后,如果你有auto result = func(param); ,其中func的类型为Callable ,您可以使用以下命令检查result的类型:

if (same_type<decltype(result), int>().value)
{
    // code, knowing that result is of type int
}
else if (same_type<decltype(result), const char*>().value)
{
    // code, knowing that result is of type const char*
}
// else if ... etc.

我尝试了各种方法,但在VS2010中对C ++ 11的支持只是部分的,大多数方法都没有编译。

最终的工作(在VS2010上)如下:

// When arity is known
typedef decltype(callbackInstance0())            return_type0; 
typedef decltype(callbackInstance1(argInstance)) return_type1;

其中callbackInstanceX是要使用的实际可调用对象, argInstance是要传递给callbackInstance的实际arg。

请注意,这不是一般解决方案(虽然在我的情况下足够),因为:

  • 它不能在没有这些类型的实际实例的函数之外使用,而只能在类定义中使用类型;
  • 必须知道可赎回的精神。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM