在 class 模板之外为指针定义一个函数
Define a function outside a class template for pointers
我想只为指针模板参数和其他参数类型定义一个成员函数。我尝试了以下代码:
#include <iostream>
template <class T, class W>
struct A
{
void foo();
};
template<class T, class W> void A<T*, W*>::foo(){ std::cout << "foo" << std::endl; }
int main(){ }
不清楚为什么它不起作用。我按照它们在模板声明中指定的相同顺序放置指针模板参数。实际上 N4296::14.5.1/3 [temp.class]
:
The template argument list following the class template name in the
member definition shall name the parameters in the same order as the
one used in the template parameter list of the member.
为什么代码不起作用?我把参数按相同的顺序排列。
您必须将整个结构定义为部分特化,您不能只挑选个别成员进行特化
[temp.class.spec]
1 [...] A partial specialization shall be declared before the first use of a class template specialization that would make use of the partial specialization as the result of an implicit or explicit instantiation in every translation unit in which such a use occurs; no diagnostic is required.
#include <iostream>
template <class T, class W>
struct A
{
void foo();
};
template<class T, class W>
struct A<T*, W*>
{
void foo();
};
template<class T, class W> void A<T*, W*>::foo() { std::cout << "foo" << std::endl; }
int main() {}
我想只为指针模板参数和其他参数类型定义一个成员函数。我尝试了以下代码:
#include <iostream>
template <class T, class W>
struct A
{
void foo();
};
template<class T, class W> void A<T*, W*>::foo(){ std::cout << "foo" << std::endl; }
int main(){ }
不清楚为什么它不起作用。我按照它们在模板声明中指定的相同顺序放置指针模板参数。实际上 N4296::14.5.1/3 [temp.class]
:
The template argument list following the class template name in the member definition shall name the parameters in the same order as the one used in the template parameter list of the member.
为什么代码不起作用?我把参数按相同的顺序排列。
您必须将整个结构定义为部分特化,您不能只挑选个别成员进行特化
[temp.class.spec]
1 [...] A partial specialization shall be declared before the first use of a class template specialization that would make use of the partial specialization as the result of an implicit or explicit instantiation in every translation unit in which such a use occurs; no diagnostic is required.
#include <iostream>
template <class T, class W>
struct A
{
void foo();
};
template<class T, class W>
struct A<T*, W*>
{
void foo();
};
template<class T, class W> void A<T*, W*>::foo() { std::cout << "foo" << std::endl; }
int main() {}