【问题标题】:Function template overload puzzle函数模板重载谜题
【发布时间】:2016-01-22 03:37:04
【问题描述】:

我有一个班级和一个班级模板

class promise;

template <class... Ts>
class typed_promise;

我打算设计一个转换实用程序在它们之间进行转换

template <class... Ts>
typed_promise<Ts...> promise_cast(promise x);

template <class... Ts>
promise promise_cast(typed_promise<Ts...> x);

所以,你可以做下面的演员表

promise pms;
typed_promise<int, int> typed_pms;
auto typed_pms2 = promise_cast<int, int>(pms);
auto pms2 = promise_cast(typed_pms);

我也想支持这样的用法

auto typed_pms2 = promise_cast<typed_promise<int, int>>(pms);

相当于

auto typed_pms2 = promise_cast<int, int>(pms);

既然C++不允许偏函数模板特化,那有没有可能实现我想要的呢?如果可能,我应该怎么做?

【问题讨论】:

  • “不允许”是错误的。 “不直接支持”更像是这样。但是我在这里没有看到 技术 问题,你有两个不同的重载。只需将纯声明更改为定义,the code works。
  • 投票关闭,因为缺少问题示例。
  • @Cheersandhth.-Alf 那会是typed_promise&lt;typed_promise&lt;int, int&gt;&gt;。
  • 这在某种程度上取决于您需要做什么。您是否需要在 promise_cast 实现中访问 Ts...?
  • 如果promise 是typed_promise 的基础,则转换问题将通过自然向上转换和static_cast 来解决

标签: c++ c++11 template-meta-programming template-specialization overloading


【解决方案1】:

当重载变得棘手时,您应该考虑完全不重载的替代方案。

给函数起不同的名字,可能是add_promise_type 和erase_promise_type。那么就不需要“部分专业化”了。

template <class... Ts>
typed_promise<Ts...> add_promise_type(promise x);

template <class... Ts>
promise erase_promise_type(typed_promise<Ts...> x);

模仿类型转换通常很诱人,但这是XY problems 的雷区。您会更喜欢更简单的解决方案,它实际上更适合手头的任务。

【讨论】:

    【解决方案2】:

    分派到您可以部分专业化的类模板。

    template<class... Ts>
    struct promise_cast_impl {
        static typed_promise<Ts...> do_cast(promise) {
            // do stuff
        }
    };
    
    template<class... Ts>
    struct promise_cast_impl<typed_promise<Ts...>> {
        static typed_promise<Ts...> do_cast(promise p){
            return promise_cast_impl<Ts...>::do_cast(std::move(p));
        }
    };
    
    template<class... Ts>
    auto promise_cast(promise x) 
         -> decltype(promise_cast_impl<Ts...>::do_cast(std::move(x))){
        return promise_cast_impl<Ts...>::do_cast(std::move(x));
    }
    

    如果您不在其他任何地方使用Ts...,您可以通过编写一个仅计算来自Ts... 的返回类型的元函数来稍微简化这一点。

    【讨论】:

    • 是的。这解决了我的问题 :-) 只需将函数调用委托给我可以部分专门化的类模板。
    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 2017-05-04
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多