首页 > 解决方案 > 如何使用模板类作为同一模板类的类型参数

问题描述

我正在尝试使用与类型相同的模板类的实例化来实例化模板类。使用不同模板类的实例化的先前答案表明此代码应该可以工作:

#include <stdio.h>
#include <typeinfo>

template <class T> class pair {
private:
    T first;
    T second;
public:
    pair(T x, T y) {
        first = x;
        second = y;
    }

    void printit() {
        if (typeid(int) == typeid(T)) {
            printf("pair(%i,%i)\n", first, second);
        } else {
            printf("type not supported yet\n");
        }
    }
};
int main(int argc, char ** argv) {
    printf("simplertest\n");
    int one = 1;
    int two = 2;
    pair<int> pi(one,two);
    pair<pair<int> > pp(pi, pi); // should make pair whose members are pairs
}

但我从 g++ 得到一个错误

> g++ simplertest.cpp
simplertest.cpp: In instantiation of ‘pair<T>::pair(T, T) [with T = pair<int>]’:
simplertest.cpp:27:31:   required from here
simplertest.cpp:9:20: error: no matching function for call to ‘pair<int>::pair()’
     pair(T x, T y) {
                    ^
simplertest.cpp:9:5: note: candidate: pair<T>::pair(T, T) [with T = int]
     pair(T x, T y) {
     ^~~~
simplertest.cpp:9:5: note:   candidate expects 2 arguments, 0 provided
simplertest.cpp:4:26: note: candidate: constexpr pair<int>::pair(const pair<int>&)
 template <class T> class pair {
                          ^~~~
simplertest.cpp:4:26: note:   candidate expects 1 argument, 0 provided
simplertest.cpp:4:26: note: candidate: constexpr pair<int>::pair(pair<int>&&)
simplertest.cpp:4:26: note:   candidate expects 1 argument, 0 provided
simplertest.cpp:9:20: error: no matching function for call to ‘pair<int>::pair()’
     pair(T x, T y) {
                    ^
simplertest.cpp:9:5: note: candidate: pair<T>::pair(T, T) [with T = int]
     pair(T x, T y) {
     ^~~~
simplertest.cpp:9:5: note:   candidate expects 2 arguments, 0 provided
simplertest.cpp:4:26: note: candidate: constexpr pair<int>::pair(const pair<int>&)
 template <class T> class pair {
                          ^~~~
simplertest.cpp:4:26: note:   candidate expects 1 argument, 0 provided
simplertest.cpp:4:26: note: candidate: constexpr pair<int>::pair(pair<int>&&)
simplertest.cpp:4:26: note:   candidate expects 1 argument, 0 provided
> g++ --version
g++ (SUSE Linux) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我在这里做错了什么?

标签: c++templatesg++

解决方案


问题是您在构造函数中使用赋值而不是初始化。pair

pair(T x, T y) 
{ //here
    first = x;
    second = y;
}

到达左括号(标有注释)时,必须初始化类中的所有数据成员。具有默认初始化程序,因此-
int没有问题,并且被默认初始化,然后在您的构造函数主体中被覆盖。 但是,不提供默认构造函数。当您尝试(so is of type )并且无法初始化时,因此出现错误。pair<int>firstsecond
pairpair<pair<int>>Tpair<int>firstsecond

解决方案是使用成员初始化列表

pair(T x, T y) : first{x}, second{y}
{
}

推荐阅读