模板<>用于专门化成员函数

时间:2019-12-23 20:08:30

标签: c++ templates template-specialization

我搞砸了专业知识,看下面的东西会编译什么

#include <iostream>
#include <typeinfo>

template <typename T>
struct base {
    void foo() { std::cout << "foo" << std::endl; }
    void bar() { std::cout << "bar" << std::endl; }
};
template<> //doesn't seem to do anything here
void base<int>::foo() 
{
    std::cout << "test1" << std::endl;
}
template<> //or here
void base<int>::bar() {
    std::cout << "test2" << std::endl;
}
int main() {
    base<int> i;
    i.foo();         // int
    i.bar();         // bar
}

在发生template<>的两个地方,无论我是否同时包括两个或两个都不输出,输出保持不变:

test1
test2

我知道,一旦模板专门化,就不再使用template<>。但是我还没有专门针对int使用它,我只是为其实现了成员函数。 template<>在这种情况下会做什么,代码有什么区别?我认为在这种情况下template<>是必要的。

我正在使用VS2019作为参考

0 个答案:

没有答案