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

Overloading member functions of class template with enable_if's

本文关键字:成员 函数 enable if 重载 使用      更新时间:2023-10-16

可能的重复项:
std::enable_if 有条件地编译成员函数

我正在尝试重载特定类型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()

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