功能模板超载难题

时间:2016-01-22 03:37:04

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

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

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 ++不允许部分函数模板专业化,是否有可能实现我想要的?如果可能的话,我该怎么做?

2 个答案:

答案 0 :(得分:3)

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

为函数指定不同的名称,可能是add_promise_typeerase_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的雷区。你会对一个更简单的解决方案更开心,这个解决方案实际上更具体针对手头的任务。

答案 1 :(得分: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...计算返回类型的元函数来略微简化此操作。