c++ - 是否可以专门研究某些(不是全部)类模板参数?

标签 c++ templates specialization

是否可以专门处理某些(不是全部)类模板参数?

例如:

template <typename T, typename U>
class TC
{
public:
 void Foo();
};

template <typename T, typename U>
void TC<T, U>::Foo()
{

}

template <???, typename U>
void TC<int, U>::Foo()
{
  //Want this defined for all U but only when T is int.
}

int main(int argv, char * args [])
{
 TC<int, char> tc;
 return 0;
}

最佳答案

通常,您可以仅特化类模板的某些模板参数,这称为“部分特化”。执行此操作时,您将创建一个新的专用模板版本,“覆盖”通用版本。

在您的情况下,您似乎只想专门化模板的一部分,即 Foo() 方法,但这是不可能的。您必须专门化整个 TC 类:

// specialization for T=int
template <typename U>
class TC<int, U> {
public:
  void Foo();
};

// implementation of Foo() for the specialized template
template <typename U>
void TC<int, U>::Foo()
{
  //Want this defined for all U but only when T is int.
}

关于c++ - 是否可以专门研究某些(不是全部)类模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2220062/

相关文章:

python - 在两个定点表示之间转换

c++ - 通过 C++ 在 Tclsh 中即时字体着色

C++单元测试测试,使用模板测试类

C++ 模板特化链接器错误

C++ 部分特化(函数指针)

c++ - 显式特化 : syntax error?

c++ - 如何提取并检查数组元素中的第一个字符是否是字母

C++ - 特定于 gcc 的警告

c++ - 用于具有不同签名的函数的枚举切换器

c++ - 模板中的函数指针