Best alternative to a typedef for a function templ

2020-05-31 16:40发布

What I'd like to do is something like this:

template <class DataType>
DataType myFunc(DataType in)
{
   ...
}

typedef myFunc<int> myFunc_i;

myFunc_i(37);

...however, typedefs cannot be used for functions like this in C++. What I was wondering is... what are people's preferred alternatives in this case? The only ones I can think of are:

1) Just deal with it, and always use myFunc syntax 2) Manually create a wrapper function, ie

inline int myFunc_i(int in)
{
    return myFunc<int>(in);
}

This would work, but would have the downside of requiring extra maintenance, and the possibility that it would get out of sync (ie, if you change the function signature for myFunc).

Thoughts?

5条回答
倾城 Initia
2楼-- · 2020-05-31 17:01

Code Example:

#include <iostream>


template <typename T>
T sqr(T a){
    return a*a;
}

auto s = sqr<int>;
int main() {

    std::cout<<s(3.9);
    return 0;
}

prints 9, that means that used int function
auto requires c++0x, you may use real typename instead, but it's ugly and you'll need check changing signature too. Besides, this code, may disallow your compiler to inline this function

  • As for me, it's often better use full name with <>

  • In your case you need not use <> because myFunc is enough(DataType may be got from argument type)

查看更多
我命由我不由天
3楼-- · 2020-05-31 17:02

I would make a just tiny improvement over Xeo's answer.

Instead of using:

auto const myFunc_i = &myFunc<int>;

I would use

constexpr auto myFunc_i = &myFunc<int>;
查看更多
▲ chillily
4楼-- · 2020-05-31 17:16

Use decltype:

template <class DataType>
DataType myFunc(DataType in)
{
   ...
}

using myFunc_i = decltype(myFunc<int>(0));

myFunc_i(37);
查看更多
做个烂人
5楼-- · 2020-05-31 17:19

Try this:

typedef int (*myFunc_i_type)(int);
myFunc_i_type const myFunc_i = &myFunc<int>;

This will trigger a compiler error if the signature of myFunc ever changes. Making it const also prohibits reassigning. Function pointers are also callable like any normal function: myFunc_i(5).

If you don't want a compiler error but rather have it update itself, use auto (again with const):

auto const myFunc_i = &myFunc<int>;
查看更多
在下西门庆
6楼-- · 2020-05-31 17:19

Some may disagree, some may jerk their knees against this, but consider this option:

#define myFunc_i myFunc<int>

As far as macros go, this one is quite safe; the only danger is that someone could redefine or undefine it later.

Aside from that, it has all the advantages of auto const myFunc = myFunc<int>;. If you want auto but don't want to use C++0x features yet, this is a more portable way to achieve the same effect.

查看更多
登录 后发表回答