模板函数参数的默认值
Default value for template function argument
注意:我没有C++11
我需要模板函数参数的默认值,但似乎 c++将跳过默认参数的扣除...
struct mode1 {};
struct mode2 {};
template <typename T>
void myFunc(int value, T mode = mode1())
{
if(std::is_same<T, mode1>::value)
{
std::cout << "foo";
}
else if(std::is_same<T, mode2>::value)
{
std::cout << "bar";
}
}
但是我怎样才能实现,这个电话将起作用:
myFunc(20); /* Defaults to mode1 */
为什么我会使用它?因为优化...在我的现实生活中,我会在这段代码中使用它:
template <typename TokenType>
HGStringBasic Tokenize(const _ElemT* tokens, size_type uTokenIndex, size_type uIndex = 0, size_type uEndIndex = npos, TokenType tokenType = tokenTypeChar()) const
{
size_type uPosInStr;
size_type uCurrToken;
if(uEndIndex == npos)
{
uEndIndex = this->Length();
}
for( uCurrToken = 0 ; uIndex < uEndIndex ; (uIndex = uPosInStr+1), (++uCurrToken) )
{
if(std::is_same<TokenType, tokenTypeChar>::value)
uPosInStr = this->PosBrk(tokens, uIndex);
else if(std::is_same<TokenType, tokenTypeString>::value)
uPosInStr = this->Pos(tokens, uIndex);
if(uCurrToken == uTokenIndex)
{
if(uPosInStr == npos)
return this_type(&m_data[uIndex], uEndIndex - uIndex);
return this_type(&m_data[uIndex], (uPosInStr < uEndIndex ? uPosInStr : uEndIndex) - uIndex);
}
if(uPosInStr == npos)
break;
}
return this_type();
}
是的,模板节选扣除中不考虑默认值。
无法从函数默认参数的类型推导出类型模板参数
您可以添加重载,例如
template <typename T>
void myFunc(int value, T mode)
{
...
}
void myFunc(int value) {
myFunc(value, mode1());
}
相关文章:
- 当给定默认值时,为什么此模板参数推导失败
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 为什么无法在可变参数模板中将尾随模板参数指定为默认值?
- 可变参数模板和具有继承的默认值
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 在子类函数覆盖中省略具有默认值的参数
- 函数作为具有默认值的参数
- 具有另一个具有默认值的模板参数的模板推导
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 对 const 引用参数使用默认值会导致崩溃
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 指针参数的默认值
- C++中出现意外的编译错误:将默认值传递给函数参数
- 我可以在哪里放置参数的默认值
- 如何在C++中设置std::list参数的默认值?
- 具有默认值的参数的自动类型扣除
- Clang vs GCC - 可变参数模板参数包后跟默认值参数在 GCC 4.8 中有效,但在 Clang 3.5 中无
- c++变长函数中默认值参数的位置
- 将函数指针上的参数与默认值参数一起丢弃是否有效