有没有办法使用基于模板类型的值初始化变量

时间:2012-07-28 09:11:49

标签: c++ template-specialization

我有一个模板类。该类有一个私有成员变量,我希望将其预设为某个值,该值因模板类型而异。

我在考虑不同类型的不同构造函数,但由于构造函数没有参数,我不知道如何去做。

无论如何都可能吗?

谢谢,

3 个答案:

答案 0 :(得分:2)

使用traits模板并将其与值进行专门化。类似的东西:

template <typename T, typename Traits = MyTraits<T> >
class MyClass {
public:
  int Foo ()
  {
   return Traits::Value;
  }
};

template <>
class MyTraits<SomeClass>
{
public:
   static int Value = 1;
};

template <>
class MyTraits<AnotherClass>
{
public:
   static int Value = 2;
};

答案 1 :(得分:1)

你可以通过对类型的专业化来实现,最简单的形式是:

#include <iostream>

template <typename T>
struct make {
  static int value() {
    return -1; // default
  }
};

template <>
struct make<int> {
  static int value() {
    return 1; 
  }
};

template <>
struct make<double> {
  static int value() {
    return 2; 
  }
};

template <typename T>
struct foo {
  const int val;
  foo() : val(make<T>::value()) {}
};

int main() {
  std::cout << foo<int>().val << ", " << foo<double>().val << "\n";
}

但您也可以将其安排为过载:

#include <iostream>

int value(void *) {
  return -1; // default
}

int value(double *) {
  return 2;
}

int value (int *) {
  return 1;
}

template <typename T>
struct foo {
  const int val;
  foo() : val(value(static_cast<T*>(nullptr))) {}
};

int main() {
  std::cout << foo<int>().val << ", " << foo<double>().val << "\n";
}

答案 2 :(得分:0)

您可以将模板参数的映射值转换为辅助类,为您提供如下内容:

template<typename T> struct foo_helper;
template<> struct foo_helper<int>   { static int getValue() {return 1; } };
template<> struct foo_helper<float> { static int getValue() {return 2; } };
....


template<typename T> class foo 
{
   int m;
   foo():m(foo_helper<T>::getValue()){}

};
相关问题