c++ - 如何使用模板类作为同一模板类的类型参数
问题描述
我正在尝试使用与类型相同的模板类的实例化来实例化模板类。使用不同模板类的实例化的先前答案表明此代码应该可以工作:
#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.
我在这里做错了什么?
解决方案
问题是您在构造函数中使用赋值而不是初始化。pair
pair(T x, T y)
{ //here
first = x;
second = y;
}
到达左括号(标有注释)时,必须初始化类中的所有数据成员。具有默认初始化程序,因此-
int
没有问题,并且被默认初始化,然后在您的构造函数主体中被覆盖。
但是,不提供默认构造函数。当您尝试(so is of type )并且无法初始化时,因此出现错误。pair<int>
first
second
pair
pair<pair<int>>
T
pair<int>
first
second
解决方案是使用成员初始化列表:
pair(T x, T y) : first{x}, second{y}
{
}
推荐阅读
- sql - 如何在 Bigquery 中为移动应用创建用户漏斗?
- python - Python 错误:需要以下参数
- python - 一种将 psql 表(或查询)作为文件(csv、json)直接导出到 AWS S3 的方法
- python - 循环卡在最后一个条目 python
- python - ssim as custom loss function in autoencoder (keras or/and tensorflow)
- python-3.x - 熊猫数据框到数组以供进一步使用
- php - 使用 twilio 进行设置
- python - AXL Python getLine 使用模式而不是 uuid 不起作用(CUCM 11.5)
- android - 尝试将图像(或任何数据)共享到我的应用程序时,为什么我的应用程序在最近的应用程序列表中显示 2 ea?
- javascript - 更改使用 face3 创建的网格的颜色