2013-02-11 34 views
1

我得到一个SFINAE错误,下面的代码,因为它不会使用模板。我试图完善前进的结果。任何想法任何人。完美转发不拾取方法

#include <iostream> 

#include "constants.h" 


namespace perfectforwarding 
{ 
    template<class T, class U> 
    constexpr auto maximum(T&& a, U&& b) -> decltype((a > b) ? std::forward(a) : std::forward(b)) 
    { 
     return (a > b) ? std::forward(a) : std::forward(b); 
    } 
} 



int main(int argc, const char * argv[]) 
{ 

    std::cout << "Created count is: " << created_count << std::endl; 

    auto const result = perfectforwarding::maximum(5,6.0); 

    std::cout << "The maximum of 5 and 6: " << result << std::endl; 
    return 0; 
} 

布莱尔

+1

我不认为你会从那段代码中得到你想要的。 “decltype”内部的表达式是对三元运算符的评估,而三元运算符产生的表达式是两种替代方法的*常见类型*。基本上你的模板和'template auto maximum(T && x,T && y) - > std :: common_type(std :: forward(x),std :: forward(y))'一样。也就是说,它不会**选择值大于*的参数的类型。 – 2013-02-11 14:11:59

回答

6

std::forward是一个模板,你需要明确提供类型参数,如果你想让它正常工作。这是你的maximum函数模板应该怎样被改写:

template<class T, class U> 
constexpr auto maximum(T&& a, U&& b) -> 
    decltype((a > b) ? std::forward<T>(a) : std::forward<U>(b)) 
{ 
    return (a > b) ? std::forward<T>(a) : std::forward<U>(b); 
} 

这是std::forward工具是如何定义的:

template<class T> 
T&& forward(typename remove_reference<T>::type& a) noexcept 
{ 
    return static_cast<S&&>(a); 
} 

表达typename remove_reference<T>::type使这是一个非推断背景下,这可以解释为什么类型推导如果您没有明确提供类型参数T,则会失败。

+0

感谢那是什么在我的脑海中只是不在代码:) – 2013-02-11 14:07:54

+0

@BlairDavidson:我知道的感觉:-) – 2013-02-11 14:08:19

+0

删除了荒谬的评论...我需要学习如何阅读(并阅读整个答案:) – 2013-02-11 14:19:48