C ++表达式SFINAE和ostream操纵器

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

我正在尝试学习如何使用SFINAE。出于练习目的,我试图制作一个std::ostream包装器以创建自定义格式程序。

这是我的SFINAE和自定义输出类。

// Tester
template <class O>
struct is_ostreamable {
    template <class T>
    static auto check(T t) -> decltype(std::declval<std::ostream &>() << t, std::true_type());
    template <class>
    static auto check(...) -> std::false_type;

  public:
    static constexpr bool value{std::is_same_v<decltype(check<O>(0)), std::true_type>};
};

// Custom class
class CustomOutput {
    // Constructor etc...
    template <class O, class = std::enable_if_t<is_ostreamable<O>::value>>
    CustomOutput &operator<<(O o) {
        os << o;
        return *this;
    }
}

完美地说,是不启用无法通过struct打印的classoperator<<模板。但是,使用此SFINAE时,ostream机械手无法正常工作...而且我不知道为什么。

错误,和我的期望:

int main(void){
    CustomOutput{} << "hi"; // Fine

    std::vector<int> vec;
    // CustomOutput{} << vec; // Error. Expected

    CustomOutput{} << std::endl; // Error. WHY?
}

也许我错过了什么?任何帮助将不胜感激。

c++ templates c++17 sfinae
1个回答
0
投票

问题是,std::endl是功能模板;给定std::endl,则无法推导其模板参数。

作为解决方法,您可以明确指定模板参数,例如

CustomOutput{} << std::endl;
© www.soinside.com 2019 - 2024. All rights reserved.