簡體   English   中英

僅在模板化返回類型的函數模板中混合模板特化和enable_if

[英]Mixing template specialisation and enable_if in a function template with only a templated return type

我有以下代碼無法在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函數模板和顯式模板特化?

問題只是完全專業化的語法。 它應該是:

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

函數模板特化(謝天謝地!)不需要返回與非專用模板相同的類型,因此這不是問題。

實際上, enable_if與您的錯誤無關,您的代碼只是缺少專業化中的模板參數列表:

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

在旁注中,如果條件始終為真,為什么要使用enable_if (我想你的真實代碼不是這種情況,但我只是想確定:)!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM