具有模板的构造函数专业化

Constructor Specialization with Templates

#include <iostream>

using namespace std;

template <class T>
struct MyType
{
    public:

    T cont;

    MyType(T value) : cont(value) {}
    MyType(int value = 1) : cont(value) {}
    MyType(double value = 1.2) : cont(value) {}
};

int main()
{
    MyType <int> a;

    return 0;
}

这段代码给出了这些错误:

error: 'MyType::MyType(int) [with T = int]' cannot be overloaded

error: with 'MyType::MyType(T) [with T = int]'

现在,我如何专门化一些构造函数给它们默认参数?

编辑:

我需要一种无需复制粘贴每个专业的所有 class 的方法。

正在做

template <class T>
struct MyType
{
    public:

    T cont;

    MyType(T value) : cont(value) {}
    MyType(int value = 1) : cont(value) {}
    MyType(double value = 1.2) : cont(value) {}
};

int main()
{
    MyType <int> a;

    return 0;
}

你有两个相同的构造函数MyType(int value = 1)MyType(T/*int*/ value),你不能重载


I need a way to do it without copy-pasting all the class for every specialization.

你可以

#include <iostream>

using namespace std;

template <class T>
struct MyType
{
  public:
    T cont;

    MyType(T value = 1) : cont(value) {}
};

template<>
MyType<int>::MyType(int value) : cont(value + 1) {}

template<>
MyType<double>::MyType(double value) : cont(value + 2) {}

int main()
{
  MyType <int> a;
  MyType <int> aa(10);
  MyType <double> b;

  cout << a.cont << '/' << aa.cont << '/' << b.cont << endl;

  return 0;
}

但您不能为特化参数 (error: default argument specified in explicit specialization [-fpermissive]) 指定其他默认值,因为通常默认值是在声明中指定的,而不是在定义中指定的

编译执行

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall t.cc
pi@raspberrypi:/tmp $ ./a.out
2/11/3

更简单的可能是专业化:

template <class T>
struct MyType
{
public:
    T cont;

    MyType(T value) : cont(value) {}
};

template <>
struct MyType<int>
{
public:
    int cont;

    MyType(int value = 1) : cont(value) {}
};

template <>
struct MyType<double>
{
public:
    double cont;

    MyType(double value = 1.1) : cont(value) {}
};

或者,因为它似乎只是您感兴趣的默认值,您可以标记调度默认值:

template <typename T> struct tag{};

template <typename T> const T defaultValue(tag<T>) { return {}; }
inline int defaultValue(tag<int>) { return 1;}
inline double defaultValue(tag<double>) { return 1.1;}

template <class T>
struct MyType
{
public:
    T cont;

    MyType(T value = defaultValue(tag<T>)) : cont(value) {}
};