2

鉴于:

class Hokey
{
public:
    explicit C(int i): i_(i) { }

    template<typename T>
    T& render(T& t) { t = static_cast<T>(i_); return t; }
private:
    unsigned i_;
};

如果我尝试:

Hokey h(1);
string s;
h.render(s);

键盘给我一个静态演员的错误:

t.cpp: In member function 'T& Hokey::render(T&) [with T = std::string]':
t.cpp:21:   instantiated from here
Line 11: error: no matching function for call to 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(unsigned int&)'

似乎应该说没有Hokey::render匹配。

当然,如果我提供一个有效的过载,一切正常。但是鉴于下面的代码,您取消注释该行,codepad chokes 再次

string& render(string& s) const {
    ostringstream out;
    out << i_;
//  s = out.str();
    return s;
}

SFINAE不是说 - 在第一种情况下 - 渲染中的问题不应该是错误,而是缺少有效的渲染应该是错误?

4

1 回答 1

7

在重载解决期间,这不是一个错误。换句话说,它会推迟给你一个错误,直到它确定调用肯定不会工作。之后,这是一个错误。

struct example
{
    template <typename T>
    static void pass_test(typename T::inner_type); // A

    template <typename T>
    static void pass_test(T); // B

    template <typename T>
    static void fail_test(typename T::inner_type); // C
};

int main()
{
    // enumerates all the possible functions to call: A and B
    // tries A, fails with error; error withheld to try others
    // tries B, works without error; previous error ignored
    example::pass_test(5);

    // enumerates all the possible functions to call: C
    // tries C, fails with error; error withheld to try others
    // no other functions to try, call failed: emit error
    example::fail_test(5);
}

还应该注意,重载决议(以及因此 SFINAE)只查看函数签名,而不是定义。所以这总是会失败:

struct example_two
{
    template <typename T>
    static int fail_test(T x)
    {
        return static_cast<int>(x);
    }

    template <typename T>
    static int fail_test(T x)
    {
        return boost::lexical_cast<int>(x);
    }
};

int main()
{
    example_two::fail_test("string");
}

任何一个模板替换(函数签名)都没有错误,所以这两个函数都可以调用,即使我们知道第一个会失败而第二个不会。所以这会给你一个模棱两可的函数调用错误。

boost::enable_if您可以使用(或std::enable_if在 C++0x 中,等效于)显式启用或禁用函数boost::enable_if_c。例如,您可以使用以下方法修复前面的示例:

struct example_two_fixed
{
    template <typename T>
    static boost::enable_if<boost::is_convertible<T, int>, int>
        pass_test(T x) // AA
    {
        return static_cast<int>(x);
    }

    template <typename T>
    static boost::disable_if<boost::is_convertible<T, int>, int>
        pass_test(T x) // BB
    {
        return boost::lexical_cast<float>(x);
    }
};

struct empty {} no_conversion;

int main()
{
    // okay, BB fails with SFINAE error because of disable_if, does AA
    example_two::pass_test(5);

    // okay, AA fails with SFINAE error because of enable_if, does BB
    example_two::pass_test("string");

    // error, AA fails with SFINAE, does BB, fails because cannot lexical_cast
    example_two::pass_test(no_conversion);
}
于 2011-07-27T19:33:39.133 回答