C++演绎模板函数返回类型隐式调用
我使用C++0X。 我有一个带有模板返回类型的模板函数:C++演绎模板函数返回类型隐式调用,c++,templates,return,template-specialization,C++,Templates,Return,Template Specialization,我使用C++0X。 我有一个带有模板返回类型的模板函数: MyBuffer<10> buf = "1234567890"; template< class T > T getVal(); template<> MyBuffer<5> getVal<MyBuffer<5>>() { return MyBuffer<5>(buf.data()); } template<> MyBuffer&
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();
但我想知道:我可以用以下方式简化通话吗
MyBuffer<5> fiveChars = getVal<MyBuffer<5>>();
MyBuffer<10> tenChars = getVal<MyBuffer<10>>();
MyBuffer<5> fiveChars = getVal();
MyBuffer<10> tenChars = getVal();
当然我有编译器错误
因此,我的问题是:
是否可以以某种方式声明我的模板,以便能够使用最后的代码段?我不指定GETVAL模板类型,但是编译器应该看到,我将它分配给模板类型的具体类型。
首先,您不能从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>();
您可以在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; }
及
您可以让getVal返回一个带有模板操作符MyBuffer的helper类;C++0X?它已经在2011年出版了。可能是@StoryTeller的复制品,这不是我的选择,只是依赖于项目。。。