boost :: enable_if不在函数签名 [英] boost::enable_if not in function signature

查看:248
本文介绍了boost :: enable_if不在函数签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是一个关于风格的问题:我不喜欢模板元编程的C ++方式,它要求您使用返回类型或添加一个额外的虚拟参数用于SFINAE的技巧。所以,我想出的想法是把SFINAE东西在模板参数定义本身,像这样:

This is just a question about style: I don't like the way of C++ for template metaprogramming that requires you to use the return type or add an extra dummy argument for the tricks with SFINAE. So, the idea I came up with is to put the SFINAE thing in the template arguments definition itself, like this:

#include <iostream>
#include <boost/type_traits/is_array.hpp>
#include <boost/utility/enable_if.hpp>
using namespace std;

template <typename T, typename B=typename boost::enable_if< boost::is_array<T> >::type > void asd(){
    cout<<"This is for arrays"<<endl;
}

template <typename T, typename B=typename boost::disable_if< boost::is_array<T> >::type > void asd(){
    cout<<"This is for NON arrays"<<endl;
}

int main() {
    asd<int>();
    asd<int[]>();
}

此示例使g ++抱怨:

This example make g++ complain:


../ src / afg.cpp:10:97:错误:redefinition'template void asd()'

../src/afg.cpp:10:97: error: redefinition of ‘template void asd()’

SFINAE本身工作,因为如果我删除例如 disable_if 的那个,编译器错误是:

SFINAE there itself works, because if I delete for example the one with disable_if, the compiler error is:


../ src / afg.cpp:15:12:错误:没有匹配的函数调用'asd()'

../src/afg.cpp:15:12: error: no matching function for call to ‘asd()’

这是我想要的。

所以,有没有办法完成SFINAE不在正常函数的签名,即返回类型+参数列表?

So, is there a way to accomplish SFINAE not in the "normal" signature of a function, that is return type + argument list?

编辑:
这是到底我要在真正的代码中尝试:

This is in the end what I'm going to try in the real code:

#include <iostream>
#include <type_traits>
using namespace std;

template <typename T, typename enable_if< is_array<T>::value, int >::type =0 > void asd(){
    cout<<"This is for arrays"<<endl;
}

template <typename T, typename enable_if< !is_array<T>::value, int >::type =0 > void asd(){
    cout<<"This is for NON arrays"<<endl;
}

int main() {
    asd<int[]>();
    asd<int>();
}

我使用c ++ 0x东西而不是boost,因为只要我需要

I use c++0x stuff instead of boost because as long as I need c++0x for using defaults of template arguments, I see no reason to use boost, which is its precursor.

推荐答案

默认情况下,使用默认的模板参数,模板参数不是函数模板的签名的一部分。但是模板参数的类型是。因此,您可以执行以下操作并可以重载它

Default template arguments are not part of the signature of function templates. But the type of template parameters is. So you can do the following and be able to overload it

template <
  typename T,
  typename boost::enable_if< 
    boost::is_array<T>, int 
  >::type = 0
> 
void asd() {
    cout<<"This is for arrays"<<endl;
}

template <
  typename T, 
  typename boost::disable_if< 
    boost::is_array<T>, int 
  >::type = 0 
>
void asd() {
    cout<<"This is for arrays"<<endl;
}

这篇关于boost :: enable_if不在函数签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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