【发布时间】: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 <boost/utility/enable_if.hpp>(以及其他问题)。 -
@LucTouraille 没什么区别,但无论如何我都会包含它。
-
它确实有所作为:现在编译器会向您提供一条错误消息,该消息实际上描述了您的代码的真正问题(也就是说,您没有使用 @ 987654328@ 正确,如对所链接问题的回答所述)。
-
您将声明与定义分开,这是模板无法做到的。
标签: c++ templates sfinae enable-if