【问题标题】:Deducing the selected overloaded function type for given argument types推导给定参数类型的选定重载函数类型
【发布时间】:2015-04-28 07:14:28
【问题描述】:

在给定重载集和参数列表的情况下,是否可以确定重载决策将选择的候选函数类型?例如,给定:

char* f(int);
int f(char*);

我希望能够写出类似的东西:

overload<f, short>::type x;

声明x 类型的变量char* (*)(int)

这可能吗?我的第一直觉是这样写:

template<typename... Args>
struct overload {
    template<typename Ret>
    static auto deduce(Ret (*fptr)(Args...)) -> decltype(fptr);
};

...但这不能处理非精确匹配(即decltype(overload&lt;int&gt;::deduce(f)) 有效,但decltype(overload&lt;short&gt;::deduce(f)) 无效)。

【问题讨论】:

  • 我不认为这在C++中可以做到,你可以得到返回类型,但不能得到参数的类型。

标签: c++ templates c++11 template-meta-programming overload-resolution


【解决方案1】:

C++14 通用 lambda 来拯救:

#define wap_function(f) \
   [](auto&&... args){ return f(std::forward<decltype(args)>(args)...); }

注意这个gem也解决了一流函数模板的问题:

template<typename Lhs, typename Rhs>
auto add(const Lhs& lhs, const Rhs& rhs)
{
    return lhs + rhs;
}

std::accumulate(std::begin(array), std::end(array), 0, wrap_function(add));

【讨论】:

    【解决方案2】:

    这是从Convert overloaded function to template functor 中删除的。

    问题是,你不能将重载函数插入到模板中,因为它的类型必须是已知的,因此定义一个宏:

    #define overload_set(f, f_set) \
        template <typename ...Args> \
        struct f_set { \
            typedef decltype(f(std::declval<Args>() ...)) return_type; \
            typedef return_type (*) (Args ...) type; \
        };
    

    为您要使用的每个函数定义结构:

    overload_set(f, f_set)
    

    现在可以通过以下方式访问函数指针类型:

    typedef typename f_set<int>::type f_int;
    typedef typename f_set<char *>::type f_charptr;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多