【发布时间】: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 模板类型,但编译器应该看到,我将它分配给具有模板特化的具体类型。
【问题讨论】:
-
您可以让 getVal() 返回一个带有
template<size_t n> operator MyBuffer<n>();的辅助类 -
C++0X?它已于 2011 年出版。
-
@StoryTeller,这不是我的选择,只是取决于项目...
标签: c++ templates return template-specialization