Visual Studios 2012中的默认模板参数 [英] Default template parameter in Visual Studios 2012

查看:103
本文介绍了Visual Studios 2012中的默认模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是此问题之后的后续问题.实际的问题是,Visual Studios 2012不支持功能模板的默认模板参数 ,如

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 Studios 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

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

推荐答案

同样,传递一个值来强制返回类型也不是一个好方法,而是使用template参数:

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

这篇关于Visual Studios 2012中的默认模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆