c++ - 在模板化类中声明模板化方法

标签 c++ templates

我正在尝试将模板化方法添加到模板化类中。我提到了 this回答但是语法不起作用。我添加了第二种方法,称为 tester 我想对其进行模板化。这是我的

template <typename t,typename u>
struct foo {

    void test();

    template<typename v>
    void tester(v lhs);
};

template<typename t,typename u>
void foo<t,u>::test() {
    std::cout << "Hello World" ;
}

template<typename t,typename u>
template<typename v>
void foo<t,u>::tester<v>(v lhs) {
    std::cout << "Hello world " << lhs ;
}

int main() 
{
    foo<int,int> t;
    t.test();  
    t.tester<int>(12);
}

我收到方法 tester 的错误,这是我收到的错误

  main.cpp:20:31: error: non-type partial specialization 'tester<v>' is not allowed
 void foo<t,u>::tester<v>(v lhs) {

关于为什么我会收到此错误或我可能做错了什么有什么建议吗?

最佳答案

在下面更正的代码中内嵌注释:

#include <iostream>

template <typename t,typename u>
struct foo {

    void test();

    template<typename v>
    void tester(v lhs);
};

template<typename t,typename u>
void foo<t,u>::test() {
    std::cout << "Hello World" ;
}

/*
 * change made to this template function definition
 */
template<typename t,typename u>
template<typename v>
void foo<t,u>::tester(v lhs) {
    std::cout << "Hello world " << lhs ;
}

int main() 
{
    foo<int,int> t;
    t.test();  
    t.tester<int>(12);
}

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

相关文章:

模板调用之间的 C++ 转换

c++ - AddFontMemResourceEx

c++ - C++继承和相同的函数名称

templates - 用于 Web 开发的 QuickStart 基本布局/模板?

c++ - 可变参数模板 : unfold arguments in groups

c++ - 是否有任何常规模式可以确定将...放在模板中的位置?

c++ - OOP 中面向数据的设计

c++ - 在 Google 的 C++ 测试框架中为多个单元测试创​​建一个二进制文件

c++ - Windows CreateThread在类函数调用中,指针引用崩溃?

c++ - const 引用的类型是什么?