English 中文(简体)
模板参数默认参数是否专门化?
原标题:Can a template parameter s default argument be specialized?

在 C++ 中, 如果我有一个模板参数, 我如何才能对默认参数进行清晰的专业化? 例如, 考虑 :

template <class Key, class Value = int > class Association;

如果我要 value 默认为 float 类的 特殊 默认为 special ? 如果Key是 special ,那么数值默认为 float ,那么,如果Key是 special ,那么是否有办法实际上专门化该类别 ,如果Key是 special ,那么数值默认为 ?

我想一种方法就是用特质来做到这一点:

template <class Key> struct Traits {
  typedef int defaultValue;
}
template<> struct Traits<Special> {
  typedef float defaultValue;
}
template <class Key, class Value = Traits<Key>::defaultValue> class Association;

是否有更简洁的方法这样做,而这种方式没有涉及,而且更容易地表明,在界定协会的地方,正常违约是正常违约?

最佳回答

嗯,一个非必要的 - 精密的单班条:

#include <type_traits>

template <typename Key,
          typename Value = typename std::conditional<std::is_same<Key, Special>::value, float, int>::type>
class Association { /* ... */ };
问题回答

暂无回答




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?