我试图从成员模板函数中调用成员函数,但是它 提示成员函数没有重载。我如何解决它? 下面是测试代码。
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&)'
最佳答案
看来你想调用fun
或bar
取决于foo
的param
参数。如果您使用的是 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/