C++ overloaded function as template argument

后端 未结 4 709
生来不讨喜
生来不讨喜 2020-12-03 14:40

the simplified version of my code is here

int foo(int x)
{
  return x;
}

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

template
int ba         


        
4条回答
  •  星月不相逢
    2020-12-03 15:24

    No, you can't, because you are calling the function always with only one argument, you need a type with only one argument. Instead, you can use template by value (no typename or class)

    One argument:

    
    int foo(int x)
    {
        return x;
    }
    
    int foo(int x, int y)
    {
        return x+y;
    }
    
    typedef int (*foo_fcn)(int);
    
    template
    int bar(int k)
    {
        return unary_func(k);
    }
    
    int main()
    {
        bar(3);
        return 0;
    }
    
    

    Two arguments:

    
    int foo(int x)
    {
        return x;
    }
    
    int foo(int x, int y)
    {
        return x+y;
    }
    
    typedef int (*foo_fcn)(int, int);
    
    template
    int bar(int k)
    {
        return unary_func(k, k);
    }
    
    int main()
    {
        bar(3);
        return 0;
    }
    
    

    Both:

    
    int foo(int x) // first foo
    {
        return x;
    }
    
    int foo(int x, int y) // second foo
    {
        return x+y;
    }
    
    typedef int (*foo_fcn)(int);
    typedef int (*foo_fcn_2)(int, int);
    
    template
    int bar(int k)
    {
        return unary_func(k);
    }
    
    template
    int bar(int a, int b)
    {
        return unary_func(a, b);
    }
    
    
    int main()
    {
        bar(3,1); // compiler will choose first foo
        bar(4); // compiler will choose second foo
        return 0;
    }
    

提交回复
热议问题