This question is a followup after this one. The actual problem is that default template parameters for function templates are not supported by Visual Studios 2012 as indicated by this list.
这个问题是在这个问题之后的后续问题。实际问题是Visual Studio 2012不支持函数模板的默认模板参数,如此列表所示。
Since default template parameters are not supported by Visual Studios 2012, is there any workaround to have the same result without it? So is it possible to define a template function such as
由于Visual Studios 2012不支持默认模板参数,是否有任何解决方法可以在没有它的情况下获得相同的结果?因此可以定义模板函数,例如
template <typename T, typename Ret = T>
Ret round(T val, Ret ret = Ret()) {
return static_cast<Ret>(
(val >= 0) ?
floor(val + (T)(.5)) :
ceil( val - (T)(.5))
);
}
without the use of default template arguments? The function works as
不使用默认模板参数?该功能的作用如下
auto a = round(5.5, int()); // int a = 6
auto b = round(5.5); // double b = 6.0
1 个解决方案
#1
1
Like this, also, passing a value to force a return type is not really a nice way to do it, use the template argument instead :
同样,传递一个值来强制返回类型也不是一个很好的方法,而是使用模板参数:
#include <iostream>
#include <cmath>
template <typename Ret, typename T>
Ret round( T val ) {
return static_cast<Ret>(
( val >= 0 ) ?
std::floor( val + (T) ( .5 ) ) :
std::ceil( val - (T) ( .5 ) )
);
}
template <typename T>
T round( T val ) {
return round<T,T>( val );
}
auto a = round<int>( 5.5 ); // int a = 6
auto b = round( 5.5 ); // double b = 6.0
static_assert( std::is_same<decltype(a), int>::value, "a must be int" );
static_assert( std::is_same<decltype(b), double>::value, "b must be double" );
int main() {
std::cout << a << " " << b;
}
#1
1
Like this, also, passing a value to force a return type is not really a nice way to do it, use the template argument instead :
同样,传递一个值来强制返回类型也不是一个很好的方法,而是使用模板参数:
#include <iostream>
#include <cmath>
template <typename Ret, typename T>
Ret round( T val ) {
return static_cast<Ret>(
( val >= 0 ) ?
std::floor( val + (T) ( .5 ) ) :
std::ceil( val - (T) ( .5 ) )
);
}
template <typename T>
T round( T val ) {
return round<T,T>( val );
}
auto a = round<int>( 5.5 ); // int a = 6
auto b = round( 5.5 ); // double b = 6.0
static_assert( std::is_same<decltype(a), int>::value, "a must be int" );
static_assert( std::is_same<decltype(b), double>::value, "b must be double" );
int main() {
std::cout << a << " " << b;
}