gpt4 book ai didi

c++ - 在只有模板化返回类型的函数模板中混合模板特化和 enable_if

转载 作者:行者123 更新时间:2023-11-30 02:07:39 25 4
gpt4 key购买 nike

我有以下代码无法在 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 函数模板和显式模板特化?

最佳答案

功能模板特化(谢天谢地!)不需要返回与非特化模板相同的类型,所以这不是这里的问题。

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

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

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

关于c++ - 在只有模板化返回类型的函数模板中混合模板特化和 enable_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7597474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com