【问题标题】:Constructor Specialization with Templates带有模板的构造函数专业化
【发布时间】:2019-04-01 15:14:31
【问题描述】:
#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;
}

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

错误:'MyType::MyType(int) [with T = int]' 不能重载

错误:使用 'MyType::MyType(T) [with T = int]'

现在,我怎样才能专门为一些构造函数提供默认参数?

编辑:

我需要一种方法来做到这一点,而无需复制粘贴每个专业的所有课程。

【问题讨论】:

  • "此代码有一些错误:" 请将所述错误复制粘贴到您的问题中。

标签: c++ templates constructor specialization


【解决方案1】:

在做

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),你不能重载


我需要一种方法来做到这一点,而无需为每个专业复制粘贴所有课程。

你可以拥有

#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

【讨论】:

    【解决方案2】:

    更简单的可能是专业化:

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

    【讨论】:

    • 但是没有复制粘贴所有课程的方法吗?
    猜你喜欢
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多