【问题标题】:Overloading member functions of class template with enable_if's [duplicate]使用 enable_if 重载类模板的成员函数
【发布时间】:2012-10-01 02:03:51
【问题描述】:

可能重复:
std::enable_if to conditionally compile a member function

我正在尝试为特定类型的T 重载方法Foo<T>::bar(),如下所示——但没有成功。我会很感激指针和解决方法。

#include <cstdlib>
#include <iostream>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>

template<typename T>
struct Foo
{
    typename boost::enable_if_c<boost::is_same<char,T>::value >::type
    bar();

    typename boost::disable_if_c<boost::is_same<char,T>::value >::type
    bar();
};

template<typename T>
typename boost::disable_if_c<boost::is_same<char,T>::value >::type
Foo<T>::bar()
{
    std::cout << "I am generic ..." << std::endl;
}

template<typename T>
typename boost::enable_if_c<boost::is_same<char,T>::value >::type
Foo<T>::bar()
{
    std::cout << "I am specific ..." << std::endl;
}

int main()
{
    Foo<char> f;
    f.bar();

    return EXIT_SUCCESS;
}

ideone 上编译它会产生以下编译器错误:

prog.cpp:13: error: ‘typename boost::disable_if_c<boost::is_same::value, void>::type Foo<T>::bar()’ cannot be overloaded
prog.cpp:10: error: with ‘typename boost::enable_if_c<boost::is_same::value, void>::type Foo<T>::bar()’
prog.cpp:18: error: prototype for ‘typename boost::disable_if_c<boost::is_same::value, void>::type Foo<T>::bar()’ does not match any in class ‘Foo<T>’
prog.cpp:10: error: candidate is: typename boost::enable_if_c<boost::is_same::value, void>::type Foo<T>::bar()

【问题讨论】:

  • +1:不知道你可以在 ideone 上使用 Boost。
  • 您缺少包括:#include &lt;boost/utility/enable_if.hpp&gt;(以及其他问题)。
  • @LucTouraille 没什么区别,但无论如何我都会包含它。
  • 确实有所作为:现在编译器会向您提供一条错误消息,该消息实际上描述了您的代码的真正问题(也就是说,您没有使用 @ 987654328@ 正确,如对所链接问题的回答所述)。
  • 您将声明与定义分开,这是模板无法做到的。

标签: c++ templates sfinae enable-if


【解决方案1】:

您正在使用具有相同参数的 enable_if 和 disable_if。看起来您正在启用和禁用相同的模板实例,编译器认为您正在重载它。不要在这两种情况下都使用 is_same_char。

【讨论】:

  • 我认为enable_if 使Foo&lt;T&gt;::barT=char 时有效,而disable_ifFoo&lt;T&gt;::bar 时有效T!=char
猜你喜欢
  • 2012-01-22
  • 2013-08-07
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
相关资源
最近更新 更多