c++ - 从模板函数调用非模板函数

标签 c++ c++11 templates member-functions

我试图从成员模板函数中调用成员函数,但是它 提示成员函数没有重载。我如何解决它? 下面是测试代码。

class Test
{
public:
    template <typename T>
    void foo(int i, T param)
    {
        switch (i)
        {
        case 1:
            fun(param);
            break;
        case 2:
            bar(param);
        }
    }
    void fun(string p)
    {
        std::cout << "string: " << p << std::endl;
    }
    void bar(double p)
    {
        std::cout << "double: " << p << std::endl;
    }
};

int main() {
    Test t;
    t.foo(1, "hello");
    t.foo(2, 100.0);
    return 0;
}

error: no matching function for call to 'Test::fun(double&)'

最佳答案

看来你想调用funbar 取决于fooparam 参数。如果您使用的是 c++17,则可以使用 if constexpr 来执行此操作:

class Test
{
public:
    template <typename T>
    void foo(T param)
    {
        if constexpr (is_same_v<T,string> || is_same_v<T,const char*>)
            fun(param);
        else if (is_same_v<T,double>)
            bar(param);
    }

    void fun(string p)
    {
        std::cout << "string: " << p << std::endl;
    }

    void bar(double p)
    {
        std::cout << "double: " << p << std::endl;
    }
};

int main() {
    Test t;
    t.foo("hello");
    t.foo(100.0);
    return 0;
}
foo

int i参数这里不用,你决定调用哪个fun/bar基于param类型。

关于c++ - 从模板函数调用非模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55760733/

相关文章:

c++ - unique_ptr 编译错误

c++ - Cevelop——在编译时从环境变量设置 C++ 宏值?

c++11 - 带有部分模板特化的 static_assert

c++ - std::array 与用于连续内存的 C 样式数组

c++ - 函数模板不是普通函数

django - 如何重用 Django 模板?

C++ 如何使 template<T>f() 为整数 T 返回 -1,为指针类型返回 nullptr

c++ - 使用 FBO 绘制到渲染缓冲区

c++ - 带 map 的 Boost::multi_index

c++ - C++ Actor 系统的消息接收