template <typename T> class foo
{
private:
T m_var;
public:
foo(T init_var)
{
m_var = init_var;
}
foo(int init_var)
{
m_var = init_var + 1;
}
};
int main()
{
foo1 = foo<int>(3); // foo1.m_var is 4
foo2 = foo<char>('a'); // foo2.m_var is a
return 0;
}
Can I specialize template class constructor like this? Class foo works on types generaly, but when its constructor called, it works diffrently as the type of parameter. I want to use template if I can, but I see the answer which is saying 'Cant use template in constructor'.
You can have a different constructor be called when the template argument type is int
by adding a specialization.
template <typename T>
class foo
{
private:
T m_var;
public:
foo(T init_var)
{
m_var = init_var;
}
};
template<>
foo<int>::foo(int init_var)
{
m_var = init_var + 1;
}
It may be easier to delegate the increment-if-int behavior to a separate component that does just that:
template <typename T>
struct IncrementIfInt
{
const T& operator()(const T& value) { return value; }
};
template <>
struct IncrementIfInt<int>
{
int operator()(int value) { return value + 1; }
};
template <typename T> class foo
{
private:
T m_var;
public:
foo(T init_var)
: m_var(IncrementIfInt<T>()(init_var))
{
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.