代码之家  ›  专栏  ›  技术社区  ›  Adi Shavit

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

  •  2
  • Adi Shavit  · 技术社区  · 12 年前

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

    我知道 Callable 确实创建了一个可调用对象,并且通常是lambda。
    在我的特定案例中,我还知道参数的数量(arity)和类型(仅一个)。

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

    3 回复  |  直到 12 年前
        1
  •  4
  •   aschepler    12 年前

    看见 std::result_of .

    假装对象是用一个 int 你可以这样做:

    using return_type = typename std::result_of<Callable(int)>::type;
    
        2
  •  1
  •   Community Mohan Dere    9 年前

    这通常是不可能的。

    有多种方法可以调用类型,包括lambdas和 struct 那是超载吗 operator() .

    C++没有像C#这样的语言那样的反射类型,也不可能使用C++提供的工具。

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

    如果你真的想根据结果的类型来做一些事情,那么 this question 可能会有所帮助。

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

    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.
    
        3
  •  0
  •   Adi Shavit    12 年前

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

    最终(在VS2010上)奏效的是:

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

    哪里 callbackInstanceX 是要使用的实际可调用对象 argInstance 是要传递给的实际参数 callbackInstance .

    请注意,这不是一个通用的解决方案(尽管在我的情况下已经足够了),因为:

    • 如果您没有这些类型的实际实例,而只有类型,则不能在函数外部使用,如在类定义中;
    • 必须知道可调用的arity。