使函数接受可选内容以接受非可选内容吗?

时间:2018-08-21 08:56:09

标签: c++ templates c++17 optional template-deduction

我正在尝试在std::optional上以monad风格编写语法糖。请考虑:

template<class T>
void f(std::optional<T>)
{}

按原样,即使存在{{1}的转换,也不能使用非可选的T 1 (例如int)调用此函数。 }到T 2

是否有一种方法可以使std::optional<T>接受fstd::optional<T>(在调用者站点转换为可选的字符),而又不定义重载 3


1) Tf(0)error: no matching function for call to 'f(int)',(demo)。
2)因为模板参数推导不考虑转换。
3)对于一元函数,重载是可以接受的解决方案,但是当您拥有note: template argument deduction/substitution failed之类的二进制函数时,重载就变得很烦人,对于三元,四进制, etc。函数。

4 个答案:

答案 0 :(得分:37)

另一个版本。这不涉及任何内容:

template <typename T>
void f(T&& t) {
    std::optional opt = std::forward<T>(t);
}

类模板参数推论已经在这里做了正确的事情。如果toptional,将优先考虑使用复制扣除候选者,并且返回相同的类型。否则,我们将其包装。

答案 1 :(得分:15)

而不是采用可选参数作为自扣模板参数:

template<class T>
struct is_optional : std::false_type{};

template<class T>
struct is_optional<std::optional<T>> : std::true_type{};

template<class T, class = std::enable_if_t<is_optional<std::decay_t<T>>::value>>
constexpr decltype(auto) to_optional(T &&val){
    return std::forward<T>(val);
}

template<class T, class = std::enable_if_t<!is_optional<std::decay_t<T>>::value>>
constexpr std::optional<std::decay_t<T>> to_optional(T &&val){
    return { std::forward<T>(val) };
}

template<class T>
void f(T &&t){
    auto opt = to_optional(std::forward<T>(t));
}

int main() {
    f(1);
    f(std::optional<int>(1));
}

Live example

答案 2 :(得分:13)

这使用了我最喜欢的类型特征之一,它可以针对某个类型检查所有的全类型模板,以查看它是否是它的模板。

#include <iostream>
#include <type_traits>
#include <optional>


template<template<class...> class tmpl, typename T>
struct x_is_template_for : public std::false_type {};

template<template<class...> class tmpl, class... Args>
struct x_is_template_for<tmpl, tmpl<Args...>> : public std::true_type {};

template<template<class...> class tmpl, typename... Ts>
using is_template_for = std::conjunction<x_is_template_for<tmpl, std::decay_t<Ts>>...>;

template<template<class...> class tmpl, typename... Ts>
constexpr bool is_template_for_v = is_template_for<tmpl, Ts...>::value;


template <typename T>
void f(T && t) {
    auto optional_t = [&]{
        if constexpr (is_template_for_v<std::optional, T>) {
            return t; 
        } else {
            return std::optional<std::remove_reference_t<T>>(std::forward<T>(t));
        }
    }();
    (void)optional_t;
}

int main() {
    int i = 5;
    std::optional<int> oi{5};

    f(i);
    f(oi);
}

https://godbolt.org/z/HXgoEE

答案 3 :(得分:5)

另一个版本。这不涉及写特质:

template <typename T>
struct make_optional_t {
    template <typename U>
    auto operator()(U&& u) const {
        return std::optional<T>(std::forward<U>(u));
    }
};

template <typename T>
struct make_optional_t<std::optional<T>> {
    template <typename U>
    auto operator()(U&& u) const {
        return std::forward<U>(u);
    }
};

template <typename T>
inline make_optional_t<std::decay_t<T>> make_optional;

template <typename T>
void f(T&& t){
    auto opt = make_optional<T>(std::forward<T>(t));
}