gpt4 book ai didi

c++ - 模板类中方法的完全特化

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:24:27 25 4
gpt4 key购买 nike

这个主题可能存在,但命名这个特定问题的方式令人困惑。

我有以下代码 - 前三分之一是在 hpp 文件中,第二个三分之一在 impl 文件中,最后一位在 cpp 中。如果我删除注释掉的代码,它会因为我无法理解的原因而无法编译。

为什么编译器不提示我拥有的其他特化,或者为什么它不能确定第 45 行是我的代码所在的位置?

错误:

test.cpp:45:23: error: no function template matches function template specialization 'foo'
int const A<int,int>::foo(int const & rhs) {
^
test.cpp:58:5: error: call to 'foo' is ambiguous
A<int, int>::foo( test_int );
^~~~~~~~~~~~~~~~
test.cpp:21:22: note: candidate function
static int const foo(int const & rhs);
^
test.cpp:45:23: note: candidate function
int const A<int,int>::foo(int const & rhs) {
^
2 errors generated.

代码:

#include <iostream>

template <typename X, typename Y>
struct A {
static X const foo(Y const & rhs);
};

template <typename X>
struct A<X,int> {
static X const foo(int const & rhs);
};

template <typename Y>
struct A<int, Y> {
static int const foo(Y const & rhs);
};


template <>
struct A<int,int> {
static int const foo(int const & rhs);
};


//----------------------------------------

template <typename X, typename Y>
X const A<X,Y>::foo(Y const & rhs) {
X ret;
return ret;
};

template <typename X>
X const A<X,int>::foo(int const & rhs) {
X ret;
return ret;
};

template <typename Y>
int const A<int, Y>::foo(Y const & rhs) {
return 42;
};

//If I uncomment the following line, the compiler barfs
//template <>
int const A<int,int>::foo(int const & rhs) {
return rhs;
};




int main() {
std::string test_str;
int test_int;
A<int,std::string>::foo( test_str );
A<std::string,int>::foo( test_int );
A<std::string,std::string>::foo( test_str );
A<int, int>::foo( test_int );
};

最佳答案

一个完整的特化不是一个模板,而是一个类。当您输入时:

template <>
int const A<int,int>::foo(int const & rhs) {
return rhs;
};

编译器发现您想要特化 ( template <> ) 模板的成员函数 A这需要两个参数。您尝试专门化的成员用于模板的专门化,其中两个参数都是 int .编译器试图找到最佳匹配但找不到,因为有两个同样好的候选者:A<X,int>A<int,Y>可以使用该成员函数特化。那时它放弃了。

由于您要提供的是 A<int,int> 的成员定义,这是一个完整的特化(不再是模板),您需要使用通常的语法:return type::member(args):

int const A<int,int>::foo(int const & rhs) {
return rhs;
};

关于c++ - 模板类中方法的完全特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21421463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com