条件模板默认值

时间:2018-03-25 21:29:59

标签: c++ templates conditional

假设我有一个返回随机数的函数。

//defines the max value's interval
enum class Type {
    INCLUSIVE,
    EXCLUSIVE
};

template<typename T = int, Type Interval = Type::EXCLUSIVE>
T rand(const T min, const T max);

目前按预期工作,用法如下:

int result = rand(1,6); //returns an int [1, 6)
double result = rand(1.0, 6.0); //returns a double [1.0, 6.0)
int result = rand<int, Type::INCLUSIVE>(1, 6); // returns an int [1, 6]
double result = rand<double, Type::INCLUSIVE>(1.0, 6.0); //returns a double [1.0, 6.0]

我希望Interval具有默认值,具体取决于传递T的内容。例如,如果Tint,则{{1}将是Interval。如果EXCLUSIVE是双重(或浮点),则T将为Interval

我尝试使用INCLUSIVE,如此:

std::conditional

预期行为是:

template<typename T = int, typename Type Interval = std::conditional<std::is_integral<T>::value, Type::EXCLUSIVE, Type::INCLUSIVE>::type>
T RandomNumber(const T min, const T max);

我无法让它工作,因为我得到int result = rand(1,6); //returns an int [1, 6) double result = rand(1.0, 6.0); //returns a double [1.0, 6.0] //with the possibility of still overriding the default behavior e.g. int result = rand<int, Type::INCLUSIVE>(1,6); //returns an int [1, 6] C2783

有没有其他方法可以做到这一点,还是我做错了?

0 个答案:

没有答案