我试图从一个成员模板函数中调用一个成员函数,但是它抱怨一个成员函数没有重载。我该怎么解决呢?下面是测试代码。
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;
}错误:没有调用“Test::fun(double&)”的匹配函数
发布于 2019-04-19 11:08:14
似乎您想要调用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的foo参数,您可以根据param类型决定调用哪个fun/bar。
发布于 2019-04-19 11:06:37
对于给定类型的typename T,只有在函数体中的每条语句都是有效的情况下,才能实例化函数模板。特别是,这包括您的fun和bar调用。
要修复它,您需要首先修复设计。从代码示例的出汗情况来看,我认为您需要类似于:
void foo(double param)
{
bar(param);
}
void foo(string param)
{
fun(param);
}https://stackoverflow.com/questions/55760733
复制相似问题