尝试使用C++
我有一个模板函数,该功能将数组引用作为一个参数:
template<typename T, int arrSize>
void foo(T (&pArr)[arrSize]) {
cout << "base template function" << endl;
}
我想专门为c弦乐提供此功能:
template<const char *, int arrSize>
void foo(const char * (&pArr)[arrSize]) {
cout << "specialized template function" << endl;
}
我尝试实例化基础和专业化:
int main(int argc, const char **argv) {
float nums[] = {0.3, 0.2, 0.11};
const char *words[] = {"word1", "word2"};
foo(nums);
foo(words);
}
但是我似乎只能获得基础实例化:
./foo
base template function
base template function
我已经编译了此功能在Mac上使用clang ++和-STD = C ++ 17。
I have a templated function, which takes an array reference as a parameter:
template<typename T, int arrSize>
void foo(T (&pArr)[arrSize]) {
cout << "base template function" << endl;
}
I want to specialize this function for C-strings:
template<const char *, int arrSize>
void foo(const char * (&pArr)[arrSize]) {
cout << "specialized template function" << endl;
}
I try to instantiate the base and the specialization:
int main(int argc, const char **argv) {
float nums[] = {0.3, 0.2, 0.11};
const char *words[] = {"word1", "word2"};
foo(nums);
foo(words);
}
But I only seem to get the base instantiation:
./foo
base template function
base template function
I have compiled this on a Mac using clang++ with -std=c++17.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
您正在定义一个过载,期望不可用的
char const*
nontype参数。Try:
You were defining an overload expecting a non-deducible
char const*
non-type parameter.问题是您提供的第二个超载函数模板具有类型的非类型模板参数
const char*
无法为从函数参数推导。因此,要调用此超载版本,我们必须明确提供与此非类型参数相对应的模板参数。到 solve 这只需删除第一个非类型模板参数,如图所示 plower
: a href =“ https://onlinegdb.com/wnq4c2gw6” rel =“ nofollow noreferrer”> demo
另外,还请注意,功能模板不能部分专业化,但可以完全专业化,或者它们可以被超载。
The problem is that the 2nd overloaded function template that you've provided has a non-type template parameter of type
const char*
that cannot be deduced from the function parameter. So to call this overloaded version we have to explicitly provide the template argument corresponding to this non-type parameter.To solve this just remove the first non-type template parameter as shown below:
Demo
Also note that function templates cannot be partially specialized but they can be fully specialized or they can be overloaded.