按参数C++类型专门化重载构造函数

Specialize overloaded constructor by type of parameter C++

本文关键字:重载 构造函数 专门化 类型 参数 C++      更新时间:2023-10-16
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;
}

我可以像这样专门化模板类构造函数吗?类 foo 适用于一般类型,但是当调用其构造函数时,它的工作方式与参数类型不同。如果可以的话,我想使用模板,但我看到的答案是"不能在构造函数中使用模板"。

当模板参数类型int时,可以通过添加专用化来调用不同的构造函数。

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;
}

现场演示

将 increment-if-int 行为委托给一个单独的组件可能会更容易,该组件只执行此操作:

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))
  {
  }
};