c++ - 您能否为具有非类型参数的模板类型部分特化模板

标签 c++ templates partial-specialization

我认为问这个问题最简单的方法是先给出代码示例(我已经在 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/

相关文章:

c# - 在 C# 中序列化/编码简单对象以通过网络发送,供非托管 C++ 应用程序读取

c++ - 为什么 `std::reference_wrapper` 秒内不能推导出模板实例?

c++ - 使用可变参数专门化和/或重载成员函数模板

c++ - 使用模板管理 glUniform 函数

C++ 代码与模板方法调用混淆

c++ - C++ 中的特殊友元函数

C++:不允许 void 的部分函数特化 - 替代解决方案?

c++ - 列表容器 - 使用不相关的类型存储和移除

c++ - OpenGL 中的缓冲区到底是什么,我如何使用多个缓冲区来发挥我的优势?

c++ - Plesk 管理面板 C/C++ API 示例