无法获得方法存在检测机制的工作

问题描述 投票:3回答:1

我正在编写模板化代码,需要调用它获得的某些模板化operator()函数 - 但前提是operator()存在。

我写了以下代码:


template <typename>
struct sfinae_true : std::true_type{};

template <class F, typename T, typename... Us>
static auto test_templated_invoke_operator(int) ->
    sfinae_true<decltype(std::declval<F>().template operator()<T>(std::forward(std::declval<Us>())... ))>;

template <class, typename, typename... Us>
static auto test_templated_invoke_operator(long) -> std::false_type;

template <class F, typename T, typename... Us>
struct has_templated_invoke_operator : decltype( test_templated_invoke_operator<F, T, Us...>(int{}) )
{ };

template <bool ActuallyInvoke, typename R, class F, typename T, typename... Ts>
struct invoke_if_possible_inner;

template <class F, typename R, typename T, typename... Ts>
struct invoke_if_possible_inner<false, R, F, T, Ts...>
{
    R operator()(F, Ts&&...) { 
        return R(); 
    }
};

template <class F, typename R, typename T, typename... Ts>
struct invoke_if_possible_inner<true, R, F, T, Ts...>
{
    R operator()(F functor, Ts&&... params)
    {
        return functor.template operator()<T>(std::forward<Ts>(params)...);
    }
};

template <typename T, typename R>
struct invoke_if_possible {
    template <class F, typename... Ts>
    R operator()(F functor, Ts&&... params)
    {
        constexpr bool actually_invoke = has_templated_invoke_operator<F, T, Ts...>::value;
        // static_assert(actually_invoke == true,"Should be able to invoke for now!");
        return invoke_if_possible_inner<actually_invoke, R, F, T, Ts...>{}(functor, std::forward<Ts>(params)...);
    }
};

这是一个小的main()函数来测试它:

int main() 
{
    invoke_if_possible<int, double> iip;
    auto result = iip(foo{}, 3.0);
    std::cout << "Invoke if possible result is " << result << " (and should be 6.0)" << std::endl;
}

这个fails(Coliru) - 返回0.0而不是6.0。

我的问题是:为什么代码不调用定义的operator()?我如何修复检测机制,以便确认其存在并调用它?

笔记:

  • 模板参数T是任意的;它与Us参数无关。
  • 是的,可以使用operator()的返回类型派生R - 但仅限于它存在。所以我们只提供它。
  • 如果启用静态断言 - 它会失败。
c++ c++14 template-meta-programming conditional-compilation
1个回答
4
投票

你的问题在这里:

std::forward(std::declval<Us>())

std::forward采用一个非推断的模板参数,你没有提供 - 必须是forward<T>(u) - 所以它的演绎无条件失败。

但你甚至根本不需要forward。只需declval<Us>()就够了。

© www.soinside.com 2019 - 2024. All rights reserved.