C++ Identifier类构造函数匹配问题:优先选择模板构造函数的方案
问题:让编译器优先选择Identifier的模板构造函数
我正在实现一个本质为不可变字符串的Identifier类,它在内存中维护单个常量字符数组,适合需要频繁比较的标识符。
以下是我编写的构造函数:
// Default constructor for Identifier. Identifier(); // Constructor for Identifier that takes a const char* and its size. // This constructor is used to create an Identifier from a given string and size. Identifier(const char* str, uint16_t size); // Constructor for Identifier that takes a string literals. // This constructor is used to create an Identifier from a string literals. template <size_t Len> Identifier(const char(&str)[Len]) : Identifier(str, Len - 1) { std::cout << "template" << std::endl; } // Constructor for Identifier that takes a const char*. Identifier(const char* str);
我期望的使用方式如下:
// using the template constructor Identifier id = "identifier"; // using the const char* constructor const char* str = "Identifier"; Identifier id = str;
但运行测试程序时,编译器总是倾向于选择非模板构造函数,导致模板构造函数从未被调用。我需要一个解决方案,让编译器优先选择模板构造函数。
问题解决
重新梳理设计后,发现创建Identifier的最佳方式是同时传入数据和长度。
内容的提问来源于stack exchange,提问作者X1ngChui
相关产品推荐
相关产品推荐

