Best alternative to a typedef for a function template?

前端 未结 5 1570
你的背包
你的背包 2021-02-07 03:59

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

template 
DataType myFunc(DataType in)
{
   ...
}

typedef myFunc myFunc_i;

myFunc         


        
相关标签:
5条回答
  • 2021-02-07 04:41

    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>;
    
    0 讨论(0)
  • 2021-02-07 04:46

    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>;
    
    0 讨论(0)
  • 2021-02-07 04:46

    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.

    0 讨论(0)
  • 2021-02-07 04:47

    Use decltype:

    template <class DataType>
    DataType myFunc(DataType in)
    {
       ...
    }
    
    using myFunc_i = decltype(myFunc<int>(0));
    
    myFunc_i(37);
    
    0 讨论(0)
  • 2021-02-07 04:51

    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)

    0 讨论(0)
提交回复
热议问题