天天看點

Type Selection先上代碼應用

文章目錄

  • 先上代碼
  • 應用

先上代碼

#include <iostream>

using namespace std;

template <bool flag, typename T, typename U>
struct Select
{
    typedef T Result;
};

template <typename T, typename U>
struct Select<false, T, U>
{
    typedef U Result;
};

template<class T>
void f(T*)
{
    cout << "pointer version.\n";
}

template<class T>
void f(T)
{
    cout << "non-pointer version.\n";
}

int main(int argc, char* argv[])
{
    int i = 0;
    f(Select<true, double, double*>::Result(i));
    f(Select<false, double, double*>::Result(i));

    return 0;
}
           

上述代碼運作結果:

non-pointer version.
pointer version.
           

應用

例如, 我們用vector來存儲數值, 對于有多态屬性的類, 我們需要指針存儲, 非多态用值存儲. 用上述方式就可以在編譯時自動判斷, 生成對應的代碼.

繼續閱讀