不能从字符串转换到模板 C2664

问题描述 投票:0回答:1

我创造了 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++ string templates typename
1个回答
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");

这只在以下情况下有效 Tstd::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);
© www.soinside.com 2019 - 2024. All rights reserved.