【问题标题】:C++ deduce template function return type to be called implicitlyC ++推断要隐式调用的模板函数返回类型
【发布时间】:2017-07-13 11:02:19
【问题描述】:

我使用 C++0X。 我有一个带有模板返回类型的模板函数:

MyBuffer<10> buf = "1234567890";

template< class T >
T getVal();

template<>
MyBuffer<5> getVal<MyBuffer<5>>()
{
    return MyBuffer<5>(buf.data());
}

template<>
MyBuffer<10> getVal<MyBuffer<10>>()
{
    return buf;
}

因此,在一种情况下,它会在 10 秒内返回 5 个符号。 我可以通过以下方式使用它:

MyBuffer<5>  fiveChars = getVal<MyBuffer<5>>();
MyBuffer<10> tenChars = getVal<MyBuffer<10>>();

但我想知道:我是否可以简化调用,例如,通过以下方式:

MyBuffer<5> fiveChars = getVal();
MyBuffer<10> tenChars = getVal();

当然我有编译器错误。

所以我的问题: 是否可以以某种方式声明我的模板以便能够使用最后一个代码 sn-p?我没有指定 getVal 模板类型,但编译器应该看到,我将它分配给具有模板特化的具体类型。

【问题讨论】:

标签: c++ templates return template-specialization


【解决方案1】:

首先,您不能从 C++ 中的返回类型推断出任何模板参数。

如果你想减少代码量,我建议使用某种包装器:

template<int n>
MyBuffer<n> get()
{
    return getVal<MyBuffer<n>>();
}

而不是:

MyBuffer<5> fiveChars = getVal<MyBuffer<5>>();

简单使用:

auto fiveChars = get<5>();
auto tenChars = get<10>();

【讨论】:

    【解决方案2】:

    您可以在MyBuffer 中添加构造函数为您进行转换

    template <std::size_t N>
    class MyBuffer
    {
    public:
        MyBuffer(const MyBuffer&) = default;
    
        template <std::size_t M>
        /* explicit */  MyBuffer(const MyBuffer<M>& rhs) : MyBuffer(rhs.data()) {}
    
        // ...
    };
    

    然后

    MyBuffer<10> buf = "1234567890";
    
    const MyBuffer<10>& getVal() { return buf; }
    

    MyBuffer<5> fiveChars = getVal();
    MyBuffer<10> tenChars = getVal();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 2011-02-19
      相关资源
      最近更新 更多