仅在模板化返回类型的函数模板中混合模板特化和enable_if

时间:2011-09-29 12:41:12

标签: c++ templates template-specialization enable-if

我有以下代码无法在VC2010上编译:

#include <type_traits>

using namespace std;

template <class C>
typename enable_if<true, C>::type
foo()
{ return C(); }

template <>
bool
foo()
{ return true; } // error C2785: 'enable_if<true,_Type>::type foo(void)' 
                 // and 'bool foo(void)' have different return types

int main()
{
    auto a = foo<int>();
    auto b = foo<bool>();
}

错误消息似乎是错误的,因为foo()的第一个版本在功能上似乎与template <class C> C foo();完全相同。

有没有办法混合并匹配enable-if'd函数模板和显式模板特化?

2 个答案:

答案 0 :(得分:2)

问题只是完全专业化的语法。它应该是:

template <> bool foo<bool>() { return true; }
                    ^^^^^^

答案 1 :(得分:2)

函数模板特化(谢天谢地!)不需要返回与非专用模板相同的类型,因此这不是问题。

实际上,enable_if与您的错误无关,您的代码只是缺少专业化中的模板参数列表:

template <>
bool foo<bool>()
{ return true; }

在旁注中,如果条件始终为真,为什么要使用enable_if? (我想在您的真实代码中并非如此,但我只想确定:)!)

相关问题