c++ - 显式模板特化问题

标签 c++

template <class T>
class Test
{
public:
    template<class U> void f(); //generic function

    template<> void f<char>(); //Specialization for char.
};

template <class T>
template<class U> 
void Test<T>::f()   //Definition of generic function
{
}

template<>
template<> void Test<char>::f<char>(){}  //Definition of specialization.

int main()
{
    Test<char> ob1;
    ob1.f<char>(); //Works fine.

    Test<int> ob2;
    ob2.f<char>();  //Produces linker error.
}

链接器错误是

error LNK2019: unresolved external symbol "public: void __thiscall
Test<int>::f<char>(void)"

我的要求是:我应该能够将任何类型传递给测试类,并将任何类型传递给函数 f()。我应该能够使用如下所示的所有类型组合。

  Test   f()
  --------------
  int    char
  char   int
  int    int

我可以通过如下定义另一个函数来解决错误。

template<>
template<> void Test<int>::f<char>(){}

但是,将 Test 类作为 Template 有什么用呢?如何使其适用于所有组合?

最佳答案

C++03,§14.7.3/2:

显式特化应在其命名空间中声明 template 是成员,或者对于成员模板,在其命名空间中 封闭类或封闭类模板是一个成员。 成员函数、成员类或静态数据的显式特化 类模板的成员应在其命名空间中声明 类模板是一个成员。

因此您应该在类之外声明您的特化,例如:

template <class T>
class Test
{
public:
    template<class U> void f(); //generic function
};

template <class T>
template <class U> 
void Test<T>::f() {}  //Definition of generic function

template<>
template<>
void Test<char>::f<char>(){}  //Specialization.

int main()
{
    Test<char> ob1;
    ob1.f<char>();

    Test<int> ob2;
    ob2.f<char>();
}

关于c++ - 显式模板特化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062388/

相关文章:

c++ - 如何在Linux中将WCHAR []打印到文件中

c++ - 可以在没有 epsilon 的情况下将 float 与 0.0 进行比较吗?

c++ - Z3 Optimizer Unsatisfiability with Real Constraints Using C++ API

C++ 数据库连接

c++ - 链接期间模板实例发生冲突

c++ - io_context 并发提示 (BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO)

c++ - 我可以合法地写入常量 vector 指向的数据吗?把它分类?

c++ - 获取事件 udp 连接的目标 IP/端口?

c++ - 如何将多个 gsoap 客户端 web 服务编译成一个可执行文件?

c# - C++ 套接字 select() 函数返回 0 有很多连接