You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 00:00:34