我认为问这个问题最简单的方法是先给出代码示例(我已经在 ideone 上提供了它:http://ideone.com/OjK2sk):
template <typename IntType, IntType MIN_VAL, IntType MAX_VAL>
struct BoundInt
{
static constexpr IntType MIN = MIN_VAL;
static constexpr IntType MAX = MAX_VAL;
IntType value;
};
template <typename T> struct ConversionTraits;
template <typename T>
struct Value
{
// Pointless for the sake of this example
void convert()
{
ConversionTraits<T>::convert();
}
T value;
};
// this 'implementation' is also pointless for example purposes
struct ConvertImpl
{
static void convert() { }
};
template <> struct ConversionTraits<int> : public ConvertImpl {};
// This is my problem. How do I partially specialise for something that has
// constants as template parameters.
template <typename IntType>
struct ConversionTraits< BoundInt<IntType, IntType, IntType> >
{
static void convert() {}
};
int main()
{
Value<int> intval;
intval.convert();
Value<BoundInt<unsigned, 0, 100>> value;
value.convert();
}
正如评论中所指出的,我不知道如何专门化 ConversionTraits
对于 BoundInt.
编译器 (gcc 4.7) 告诉我,对于 BoundInt
的参数 2 和 3 , 它期待一个 IntType
类型的常量这是有道理的。我不知道如何执行该特化,或者是否可能。
如果不可能,我可以采用其他方法吗?
最佳答案
这个怎么样:
template <typename IntType, IntType MIN_VAL, IntType MAX_VAL>
struct ConversionTraits< BoundInt<IntType, MIN_VAL, MAX_VAL> >
{
static void convert() {}
};
它可能看起来违反直觉,因为普通的 ConversionTraits<>
模板只有 1 个参数,而特化有 3 个。
但是,模板 BoundInt<>
具有三个参数,因此如果您不想指定它们,则必须为每个参数使用一个模板参数。
关于c++ - 您能否为具有非类型参数的模板类型部分特化模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21537288/