c++ - 无法从字符串转换为模板 C2664
问题描述
我创建了List
(一个带有模板的类),它的构造函数接收一个值T
。我正在尝试在一个switch
名为Menu
(也带有模板)的类中设置这种类型的值。当我尝试运行Menu.run()
除字符串之外的所有开关选项时。
错误是
错误 C2664 'List<T>::List(const List<T> &)': 无法将参数 1 从 'const char [2]' 转换为 'T'
//Class List
template <class T>
class List {
public:
List(T value) {
this->head = nullptr;
this->tail = nullptr;
this->value = value;
this->name = "no name";
}
protected:
List* head;
List* tail;
T value;
std::string name;
};
//Class Menu
template<typename T>
class Menu{
public:
Menu(int dataType) {
this->dataType = dataType;
}
void run(){
std::map<std::string, List< T > * > list;
List< T >* list1 = new List< T >("Test");
std::cout << list1->toString() << std::endl;
}
int main(){
int dataType = 1;
if (dataType == 1) {
Menu <std::string> c(dataType);
c.run();
}else if (dataType == 2) {
Menu <int> c(dataType);
c.run();
}else if (dataType == 3) {
Menu<double> c(dataType);
c.run();
}else if (dataType == 4) {
Menu<char> c(dataType);
c.run();
}
return 0;
}
解决方案
在您的main
函数中,编译器必须编译您的所有代码。即使它稍后会优化它,因为它可以看到dataType == 1
c++ 标准说它必须首先为所有数据类型生成代码。
您可以通过使用来解决此问题,if constexpr
以便编译器仅编译实际使用的代码:
int main(){
const int dataType = 1;
if constexpr (dataType == 1) {
Menu <std::string> c(dataType);
c.run();
}else if (dataType == 2) {
Menu <int> c(dataType);
c.run();
}else if (dataType == 3) {
Menu<double> c(dataType);
c.run();
}else if (dataType == 4) {
Menu<char> c(dataType);
c.run();
}
return 0;
}
听起来这实际上不是您想要的。正确的解决方案是修复导致故障的线路:
List< T >* list1 = new List< T >("Test");
这仅在T
is时有效std::string
。如果你用更通用的东西替换它,那么你的代码将编译。您可以使用默认构造值:
List< T >* list1 = new List< T >(T{});
或者更有可能您的作业需要您从控制台读取值:
T value;
while (!(std::cin >> value))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "invalid value\n";
}
List< T >* list1 = new List< T >(value);
推荐阅读
- javascript - 检测任何可能打开链接而不知道是哪个元素的点击
- php - 如何通过php检查目录中丢失的文件
- java - Maven 中工件的访问限制(模块化)
- java - 如何使用 Spring Security 将对象从 AJAX 传递到 Spring Controller
- python - 试图读取一个大的 csv 文件并且连接速度太慢
- joomla3.0 - Joomla 自定义模块中的布局
- apache - 如果服务器安装了 nginx 和 apache,我如何找出它用于其网站的哪一个?
- azure - 从 Angular 前端调用受 Azure AD 保护的 Web API
- android - Admob 广告无法在 android 中加载
- php - 检测当前用户