Substitution failure is not an error.

该技术使得我们在定义模板函数的时候对该模板所实际实例化的类型进行较好的匹配.

 #include <iostream>
struct Test{
 using info = int;
};
template<typename T>
void f(typename T::info )
{
 //
 std::cout<<"匹配成功"<<std::endl; 
}
template<typename T>
void f(T t)
{
 std::cout<<t<<std::endl;
}
int main()
{
 f<Test>(10);
 f<int>(10);
 
 return 0;
}

 例子2:

 #include <iostream>
template <typename T>
struct has_typedef_foobar {
    // Types "yes" and "no" are guaranteed to have different sizes,
    // specifically sizeof(yes) == 1 and sizeof(no) == 2.
    typedef char yes[1];
    typedef char no[2];
    template <typename C>
    static yes& test(typename C::foobar*);
    template <typename>
    static no& test(...);
    // If the "sizeof" of the result of calling test<T>(nullptr) would be equal to sizeof(yes),
    // the first overload worked and T has a nested type named foobar.
    static const bool value = sizeof(test<T>(nullptr)) == sizeof(yes);
};
struct foo {    
    typedef float foobar;
};
int main() {
    std::cout << std::boolalpha;
    std::cout << has_typedef_foobar<int>::value << std::endl;
    std::cout << has_typedef_foobar<foo>::value << std::endl;
}

你可能感兴趣的:(Substitution failure is not an error.)