Default template parameter in Visual Studios 2012

ε祈祈猫儿з 提交于 2019-12-12 05:09:32

问题


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.


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

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:


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; 
}


来源:https://stackoverflow.com/questions/21811485/default-template-parameter-in-visual-studios-2012

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!