C++:模板参数的默认值而不是最后一个? [英] C++: Default values for template arguments other than the last ones?

查看:27
本文介绍了C++:模板参数的默认值而不是最后一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板化容器类如下所示:

I have my templated container class that looks like this:

template<
   class KeyType, 
   class ValueType, 
   class KeyCompareFunctor   = AnObnoxiouslyLongSequenceOfCharacters<KeyType>, 
   class ValueCompareFunctor = AnObnoxiouslyLongSequenceOfCharacters<ValueType> 
>
   class MyClass
   {
      [...]
   }

这意味着当我实例化这个类的一个对象时,我可以通过几种不同的方式来实现:

Which means that when I instantiate an object of this class, I can do it several different ways:

MyClass<MyKeyType, MyValueType> myObject;
MyClass<MyKeyType, MyValueType, MyCustomKeyCompareFunctor> myObject;
MyClass<MyKeyType, MyValueType, MyCustomKeyCompareFunctor, MyCustomValueCompareFunctor> myObject;

这些都很好.当我想实例化一个使用 ValueCompareFunctor 参数的非默认版本的 MyClass 时,问题就出现了,但我仍然想使用 KeyCompareFunctor 参数的默认值.那我得写这个:

Those are all good. The problem comes when I want to instantiate a MyClass that uses a non-default version of the ValueCompareFunctor argument, but I still want to use the default value of the KeyCompareFunctor argument. Then I have to write this:

MyClass<MyKeyType, MyValueType, AnObnoxiouslyLongSequenceOfCharacters<MyKeyType>, MyCustomValueCompareFunctor> myObject;

如果我能以某种方式省略第三个参数而只写这个会方便得多:

It would be much more convenient if I could somehow omit the third argument and just write this:

MyClass<KeyType, ValueType, MyCustomValueCompareFunctor> myObject;

由于 MyCustomValueCompareFunctor 仅适用于 MyValueType 类型的对象,而不适用于 MyKeyType 类型的对象,因此编译器似乎至少可以在理论上计算出我在这里的意思.

Since the MyCustomValueCompareFunctor works only on objects of type MyValueType and not on objects of type MyKeyType, it seems like the compiler could at least theoretically work out what I meant here.

有没有办法在 C++ 中做到这一点?

Is there a way to do this in C++?

推荐答案

一般来说,无论是在模板还是函数或方法中,C++ 都允许您仅对 尾随 参数使用默认值(从而省略) -- 没有出路.

In general, both in templates and functions or methods, C++ lets you use default for (and thereby omit) only trailing parameters -- no way out.

我推荐使用模板或宏将 AnObnoxouslyLongSequenceOfCharacters 缩短为 Foo —— 不完美,但总比没有好.

I recommend a template or macro to shorten AnObnoxiouslyLongSequenceOfCharacters<MyKeyType> to Foo<MyKeyType> -- not perfect, but better than nothing.

这篇关于C++:模板参数的默认值而不是最后一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆