c++ - 使用 enable_if 重载类模板的成员函数

标签 c++ templates sfinae enable-if

<分区>

Possible Duplicate:
std::enable_if to conditionally compile a member function

我正在尝试重载方法 Foo<T>::bar()对于特定类型的 T如下 - 没有成功。我会很感激指点和解决方法。

#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()

最佳答案

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

关于c++ - 使用 enable_if 重载类模板的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12822083/

相关文章:

c++ - 延迟加载 DLL

c++ - 对具有 std::map<int, T> 成员的类无效使用不完整类型

c++ - 执行 RSA 解密时密文无效

c++ - 将 QDate 转换为 Qstring?

c++ - 优化 c++/gcc 中的模板编译时间

.net - 在模板中填充数据的最佳实践?

c++ - 如果存在,如何调用模板化函数,否则如何调用?

c++ - C2995 : template already defined

c++ - 如果超过我的堆栈大小,我如何自动调整它? C++

c++ - C++中的双重继承运行时错误