Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

C++ overloaded function as template argument

the simplified version of my code is here

int foo(int x)
{
  return x;
}

int foo(int x, int y)
{
  return x+y;
}

template<typename unary_func>
int bar(int k, unary_func f)
{
  return f(k);
}

int main()
{
  bar(3, foo);
  return 0;
}

Is there a way to tell the compiler what I want to pass as argument is the first `foo'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can give an explicit template argument:

bar<int(int)>(3, foo);

or cast the ambiguous function name to a type from which the template argument can be deduced:

bar(3, static_cast<int(*)(int)>(foo));

or wrap it in another function (or function object) to remove the ambiguity

bar(3, [](int x){return foo(x);});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...