enable_if函数在不应该定义的时候定义 [英] enable_if function defined when it shouldn't be

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

问题描述

作为一个实验,我试图使一个无成员函数的void成员函数不会基于类模板参数改变行为:

As an experiment, I am trying to make a void member function with no parameters change behavior based on the class template parameter:

#include <iostream>
#include <limits>

template<typename T>
class MyClass
{
public:
  void MyFunc(const typename std::enable_if<std::is_fundamental<T>::value, T> dummy = T());
  void MyFunc(const typename std::enable_if<!std::is_fundamental<T>::value, T> dummy = T());

};

template<typename T>
void MyClass<T>::MyFunc(const typename std::enable_if<std::is_fundamental<T>::value, T> dummy)
{
}

template<typename T>
void MyClass<T>::MyFunc(const typename std::enable_if<!std::is_fundamental<T>::value, T> dummy)
{
}

class Simple {};

int main(int argc, char *argv[])
{
  MyClass<int> myClass;
  myClass.MyFunc();

//   MyClass<Simple> myClass2;
//   myClass2.MyFunc();

  return 0;
}

但是,我得到:错误:重载的"MyFunc()"的调用不明确.不应该只定义其中一个函数,因为除了!以外,其他所有函数都相同.在其中之一?

However, I am getting: error: call of overloaded ‘MyFunc()’ is ambiguous. Shouldn't only one or the other of those functions get defined, since everything is the same except for a ! in one of them?

推荐答案

您必须设置虚拟模板参数才能执行我要求的操作:

You have to make dummy template parameters to do what I was asking:

#include <iostream>
#include <limits>

template<typename T>
class MyClass
{
public:
  template <typename U = T>
  void MyFunc(const typename std::enable_if<std::is_fundamental<U>::value, U>::type dummy = U());
  template <typename U = T>
  void MyFunc(const typename std::enable_if<!std::is_fundamental<U>::value, U>::type dummy = U());
};

template<typename T>
template<typename U>
void MyClass<T>::MyFunc(const typename std::enable_if<std::is_fundamental<U>::value, U>::type dummy)
{
}

template<typename T>
template<typename U>
void MyClass<T>::MyFunc(const typename std::enable_if<!std::is_fundamental<U>::value, U>::type dummy)
{
}

class Simple {};

int main(int argc, char *argv[])
{
  MyClass<int> myClass;
  myClass.MyFunc();

  MyClass<Simple> myClass2;
  myClass2.MyFunc();

  return 0;
}

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

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