首页 > 解决方案 > 无法从字符串转换为模板 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;
}

标签: c++stringtemplatestypename

解决方案


在您的main函数中,编译器必须编译您的所有代码。即使它稍后会优化它,因为它可以看到dataType == 1c++ 标准说它必须首先为所有数据类型生成代码。

您可以通过使用来解决此问题,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");

这仅在Tis时有效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);

推荐阅读