如何修复此模板: [英] How to fix this template:

查看:106
本文介绍了如何修复此模板:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

template <typename IN,typename OUT,bool isVector>
OUT foo(IN x){
    if (isVector){
        return x[0];     
    } else {
        return x;
    }
}

在询问这个问题我错误地假设,上面的代码可以编译例如

After asking this question I wrongly assumed, that the above code could compile for e.g.

foo<double,double,false>;

以及

foo<std::vector<double>,double,true>;

然而,即使其中一个if分支不会被执行,以上不编译。如何解决?

However, even if one of the if-branches never gets executed, it is checked for correctness and thus the above does not compile. How can I fix it?

上面的代码是一个简化的,但我不知道如何解决它,因为功能模板不能有部分专业化...

The code above is a simplified, but I dont know how to fix it, as function templates cannot have partial specialization...

推荐答案

你可以提取你想要专门化的模板参数,使它们成为某些结构的模板参数,剩余模板参数作为静态成员函数:

You can "extract" the template parameters you want to specialize on, make them the template parameters of some structure, and write the function with the remaining template parameters as static member function:

template<bool IsVector = true>
struct Bar {
    template<typename In>
    static auto foo(In input) {
        return input[0];
    }
};
template<>
struct Bar<false> {
    template<typename In>
    static auto foo(In input) {
        return input;
    }
};

很明显,这会导致调用网站发生变化,您可以使用调用相应函数的自由函数捕获

Obviously this results in a change at the call site, which you can "catch" using a free function that is calling the appropriate function:

template<typename In, bool IsVector>
auto real_foo(In input) {
  return Bar<IsVector>::foo(input);
}

结构( Bar

The structures (Bar) are then normally put inside an "helper" namespace.

另一种可能性是使用标签和重载分辨率:

Another possibility is to use tags and overload resolution:

template<typename In>
auto foo(In input, std::true_type) {
    return input[0];
}
template<typename In>
auto foo(In input, std::false_type) {
    return input;
}
template<bool IsVector, typename In>
auto foo(In input) {
    using tag = typename conditional<IsVector, true_type, false_type>::type;
    return foo(input, tag{});
}

Live example。

这使用 std :: true_type 和<$ c的rel =nofollow> std :: conditional $ c> std :: false_type 作为不同类型,以允许重载解析找到适当的 foo 函数。

This uses std::conditional with std::true_type and std::false_type as different types to allow overload resolution to find the appropriate foo function.

这篇关于如何修复此模板:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆