我想你可以使用布尔默认值,比如下面例子中的foo struct
#include <iostream>
template <typename>
struct isSpecialType
{ static constexpr bool value { false }; };
template <>
struct isSpecialType<int>
{ static constexpr bool value { true }; };
template <>
struct isSpecialType<double>
{ static constexpr bool value { true }; };
template <typename T, bool = isSpecialType<T>::value>
struct foo;
template <typename T>
struct foo<T, true>
{ static constexpr bool value { true }; };
template <typename T>
struct foo<T, false>
{ static constexpr bool value { false }; };
int main()
{
std::cout << "- void value: " << foo<void>::value << std::endl;
std::cout << "- bool value: " << foo<bool>::value << std::endl;
std::cout << "- int value: " << foo<int>::value << std::endl;
std::cout << "- double value: " << foo<double>::value << std::endl;
}
这个想法是定义一种类型特征(isSpecialType)来选择所选类型(int 和 double,在您的示例中),布尔值在通用实现中为 false,@ 987654327@ 在专业领域。
template <typename>
struct isSpecialType
{ static constexpr bool value { false }; };
template <>
struct isSpecialType<int>
{ static constexpr bool value { true }; };
template <>
struct isSpecialType<double>
{ static constexpr bool value { true }; };
接下来,您必须声明 foo 结构(class Vec,在您的问题中),并带有一个补充 bool 模板值和 isSpecialType<T>::value 默认值
template <typename T, bool = isSpecialType<T>::value>
struct foo;
最后,您必须实现foo 的两个部分专用版本:第一个带有布尔值true 的版本
template <typename T>
struct foo<T, true>
{ static constexpr bool value { true }; };
对应你的Vec的专用版;具有false 布尔值的那个
template <typename T>
struct foo<T, false>
{ static constexpr bool value { false }; };
对应于您的Vec 的通用版本。
还有一点:我的例子是C++11或者更新的代码;如果您想要 C++98 版本,您只需将 bool 值定义为 const(而不是 constexpr)并将它们初始化为 C++98 样式;我是说
static bool const bool value = true;
而不是
static constexpr bool value { true };