我試圖獲得基於整數值作爲模板類型的專業化。如果我使用一個整數,專業化是直截了當的。是否有可能有一個簡單的基於範圍的模板專業化而不使用增強基礎。基於整數範圍的模板專業化
這是代表代碼轉換爲
template <typename int val>
class Param
{
public:
};
template <> class Param<0 to 100>
{
};
template <> class Param<100 to 175>
{
};
我試圖獲得基於整數值作爲模板類型的專業化。如果我使用一個整數,專業化是直截了當的。是否有可能有一個簡單的基於範圍的模板專業化而不使用增強基礎。基於整數範圍的模板專業化
這是代表代碼轉換爲
template <typename int val>
class Param
{
public:
};
template <> class Param<0 to 100>
{
};
template <> class Param<100 to 175>
{
};
是否有可能有基於一系列簡單的模板特不使用提升的基礎。
不適用於C++ 03,它非常優雅,簡潔,可維護且通用,可輕鬆指定任意大的範圍。爲了保持代碼簡潔,您需要像boost預處理程序庫一樣來遍歷一系列值。
Sans BOOST或重新實現它的大塊,你可以創建一些悲傷的小宏來調用特定數量的連續值的初始宏。例如:
#define X(N) template <> class Param<N> { ... };
#define X2(N) X(N) X(N+1)
#define X4(N) X2(N) X2(N+2)
#define X8(N) X4(N) X4(N+4)
...
// template <> class Param<100 to 175> then becomes
X64(100); // 100..163
X8(164); // 164..171
X4(172); // 172..175
或者,你可以使用一個程序/腳本編寫你的C++代碼,如較早的編譯步驟,有時可以算出更好的 - 有時更糟糕 - 比預處理兩輪牛車。
您可以使用SFINAE與std::enable_if
使自己得心應手的編譯時間範圍的測試類:
#include <iostream>
#include <type_traits>
using namespace std;
template<int Start, int End, int Val, class Enable = void>
struct crange { };
template<int Start, int End, int Val>
struct crange<Start, End, Val, typename std::enable_if<Val >= Start && Val <= End>::type> {
typedef void enabled;
};
template<int Val, class Enable = void>
class Param {
public:
Param() : value(422) { }
int value;
};
template<int Val> // V VV the range [x, y]
class Param<Val, typename crange<0, 10, Val>::enabled> {
public:
Param() : value(1.32) { }
double value;
};
int main() {
Param<1> pdouble;
Param<50> pint;
cout << pdouble.value << endl; // prints 1.32
cout << pint.value << endl; // prints 422
}
更好。非常感謝! – Ram 2012-03-01 14:46:45
很酷。雖然真的唯一的區別是你必須在每個模板類上編寫'(x
2012-03-01 14:51:54
這個問題現在有兩種方法可以爲未來的訪問者提供幫助。 + 1 btw。 – 2012-03-01 14:58:14