テンプレートクラスがあります。クラスには、テンプレートタイプごとに異なる特定の値にプリセットしたいプライベートメンバー変数があります。
型ごとに異なるコンストラクターを考えていましたが、コンストラクターにはパラメーターがないため、その方法がわかりません。
とにかく可能ですか?
ありがとう、
テンプレートクラスがあります。クラスには、テンプレートタイプごとに異なる特定の値にプリセットしたいプライベートメンバー変数があります。
型ごとに異なるコンストラクターを考えていましたが、コンストラクターにはパラメーターがないため、その方法がわかりません。
とにかく可能ですか?
ありがとう、
特性テンプレートを使用して、値で特殊化します。何かのようなもの:
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;
};
タイプに特化してそれを行うことができます。最も簡単な形式は次のとおりです。
#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";
}
テンプレートパラメータから値へのマッピングをヘルパークラスに入れて、次のようにすることができます。
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()){}
};